Object类
方法:
wait() //导致当前线程等待它被唤醒,通常是 通知或 中断 。
wait(long timeoutMillis)
wait(long timeoutMillis, int nanos)
notify() //唤醒正在此对象监视器上等待的单个线程。
notifyAll() //唤醒等待此对象监视器的所有线程。
public class Demo3 {
public static void main(String[] args) {
Food f = new Food();
Cooker c = new Cooker(f);
c.start();
Waiter w = new Waiter(f);
w.start();
}
static class Cooker extends Thread{
private Food f;
public Cooker(Food f){
this.f = f;
}
@Override
public void run() {
for (int i=0;i<100;i++){
if(i%2==0){
f.set("青椒肉丝","香辣");
}else{
f.set("土豆泥","咸香");
}
}
}
}
static class Waiter extends Thread{
private Food f;
public Waiter(Food f){
this.f = f;
}
@Override
public void run() {
for(int i=0;i<100;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
f.get();
}
}
}
static class Food{
private String name;
private String taste;
//true表示可以生产
private boolean flag = true;
//同步方法
public synchronized void set(String name,String taste){
if(flag==true){
this.name = name;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.taste = taste;
flag=false;
//唤醒所有线程
this.notifyAll();
try {
//使Cooker线程睡眠
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//同步方法
public synchronized void get(){
if(!flag){
System.out.println("服务员端走的菜名:"+name+",味道:"+taste);
flag=true;
//唤醒所有线程
this.notifyAll();
try {
//使Waiter线程睡眠
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}