日期:2014-05-20  浏览次数:20903 次

java线程同步的小问题,在线等
public class SyncDemo1 {
  public static void main(String[] args) {
  Table table = new Table();
  Person p1 = table.new Person();
  Person p2 = table.new Person();
  p1.start();
  p2.start();
  }
}
class Table{
  int beans=20;
  Object monitor = new Object(); //同步监视器, 同步锁
//boolean monitor.lock = false
  public synchronized int getBean(){
  int a = 5;
  if(beans==0)
  throw new RuntimeException("没了");
  Thread.yield();
  return beans--;
  }
  class Person extends Thread{
public void run(){
while(true){
int bean = getBean();
System.out.println(getName()+"拿到:"+bean);
Thread.yield();
}
}
}
}

上面的代码运行如下

Thread-1拿到:20
Thread-0拿到:19
Thread-1拿到:18
Thread-0拿到:17
Thread-0拿到:16
Thread-1拿到:15
Thread-1拿到:14
Thread-0拿到:13
Thread-1拿到:12
Thread-1拿到:10
Thread-0拿到:11
Thread-0拿到:9
Thread-1拿到:8
Thread-1拿到:7
Thread-0拿到:6
Thread-0拿到:4
Thread-1拿到:5
Thread-0拿到:3
Thread-1拿到:2
Thread-0拿到:1

现问:整个运行过程是怎么样的,能帮我分析下吗,thanks

------解决方案--------------------
两个Person都去调用getBean方法,因为同步了,每次只能进去一个。调用20次结束
------解决方案--------------------
public synchronized int getBean 这里实现同步,被调用后会加锁
------解决方案--------------------
3楼说的对,synchronized 保证每次只进入一个线程