用到的方法:
//Object类等待和唤醒方法
//导致当前线程等待它被唤醒,通常是 通知或 中断 。
void wait()
//导致当前线程等待它被唤醒,通常是 通知或 中断 ,或者直到经过一定量的实时。
void wait•(long timeoutMillis)
// 导致当前线程等待它被唤醒,通常是 通知或 中断 ,或者直到经过一定量的实时。
void wait•(long timeoutMillis, int nanos)
// 唤醒正在此对象监视器上等待的单个线程。
void notify() //唤醒一个或多个中随机的一个
//唤醒等待此对象监视器的所有线程。
void notifyAll() //唤醒全部
厨师-—服务员—做菜端菜代码示例 :
public class Practice {
public static void main(String[] args) {
Food f = new Food();
new Cook(f).start();
new Waiter(f).start();
}
static class Cook extends Thread {
private Food f;
public Cook(Food f) {
this.f = f;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
f.setNameAndTaste("皮蛋粥", "咸");
} else {
f.setNameAndTaste("雪糕", "甜");
}
}
}
}
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;
private Boolean flag = true;
public synchronized void setNameAndTaste(String name, String taste) {
if (flag) {
this.name = name;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.taste = taste;
flag = false;
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void get() {
if (!flag) {
System.out.println("服务员端走的菜的名字是:" + name + "味道是:" + taste);
flag = true;
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}