package Notify;
/*
线程通信:
需求:某餐厅 1个服务员 1个厨师
吧台最多放10份菜
如果厨师已经做了10份 则进行等待 通知服务员上菜
服务员上菜 当服务员已经将所有的菜都上完 服务员休息 通知厨师做菜
当吧台菜已经<0时 服务员等待
吧台菜>0 时 大厨等待
*/
public class Test {
public static void main(String[] args) {
Bar bar=new Bar();
CookThread cookThread=new CookThread();
cookThread.setName("大厨");
cookThread.setBar(bar);
cookThread.start();
WaiterThread waiterThread=new WaiterThread(bar);
waiterThread.setName("服务员");
waiterThread.start();
}
}
class WaiterThread extends Thread{
private Bar bar;
public WaiterThread(Bar bar) {
this.bar = bar;
}
@Override
public void run() {
while (true) {
synchronized (bar) {
if (bar.count<=0){
try {
bar.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bar.count--;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + "端走了一份菜,还有" + bar.count + "份菜");
//通知厨师做菜
bar.notify();
}
}
}
}
class CookThread extends Thread{
private Bar bar;
public void setBar(Bar bar) {
this.bar = bar;
}
@Override
public void run() {
while (true){
synchronized (bar){
if (bar.count>=Bar.maxnum){
try {
bar.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bar.count++;//厨师做了一道菜
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName()+"做了一道菜,现在有"+bar.count+"份菜");
//通知服务员端菜
bar.notify();
}
}
}
}
class Bar {
//只能放10份菜
public static final int maxnum=10;
//记录吧台做菜数量
int count;
}
此案例利用同步代码块实现线程通信时,是将bar.count=10的时候通知服务员进程,请问如何操作才能使厨师进程count+1时 就通知服务员进程