资源:
public class Table {
public static Integer foodCount=10;
public static Boolean hasFood=false;
public static final Object lock=new Object();
}
生产者
public class Producer extends Thread {
@Override
public void run() {
while (true){
synchronized (Table.lock){//自动释放锁
if(Table.foodCount<=0){
break;//让程序有个停止标志
}else {
if (Table.hasFood) {
try {
Table.lock.wait();//等着食物被吃完
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName()+"生产食物。。。。。");
Table.hasFood=true;
Table.lock.notify();//叫客人来吃东西
}
}
}
}
}
}
消费者
public class Customer extends Thread {
@Override
public void run() {
while (true){
synchronized (Table.lock) {
if (Table.foodCount <= 0) {
break;//让程序停止
} else {
if (Table.hasFood) {
System.out.println(Thread.currentThread().getName()+"用餐。"+
Thread.currentThread().getName()+"还可以用餐"+(--Table.foodCount)+"次");
Table.hasFood=false;
Table.lock.notify();//唤醒厨师做菜
}else {
try {
Table.lock.wait();//等着厨师做菜
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
以上是今日小节,不喜勿喷,感谢理解