package socket;
public class SyncDemo {
public static void main(String[] args) {
Table table = new Table();
Thread t1 = new Thread(){
public void run(){
while(true){
int bean = table.getBean();
System.out.println(getName()+":"+bean);
}
}
};
Thread t2 = new Thread(){
public void run(){
while(true){
int bean = table.getBean();
System.out.println(getName()+":"+bean);
}
}
};
t1.start();
t2.start();
}
}
class Table{
//20个豆子
private int beans = 20;
public int getBean(){
if(beans ==0){
throw new RuntimeException("没有豆子");
}
//模拟线程执行到这里没有时间了
Thread.yield();
return beans--;
}
}
并发问题2
最新推荐文章于 2022-03-08 00:49:34 发布