有某个线程唤醒等待中的线程,JDK1.5之前可有synchronized、wait()、notify()/notifyAll()实现,JDK1.5提供了Lock、Condition组合实现。
例如,妈妈往盘子中放一个鸡蛋,则小明拿来吃。如果盘子是空的,则小明进入等待状态,如果盘子还有鸡蛋,则妈妈进入等待状态,当妈妈放如一个鸡蛋时,唤醒小明吃,小明吃了鸡蛋之后,唤醒妈妈放鸡蛋。
package thread;
public class CommunicationThreadTest {
public static void main(String[] args) {
Egg egg = new Egg();
new MyThread(egg, "mother").start();
new MyThread(egg, "xiaoming").start();
}
}
class MyThread extends Thread {
private Egg egg;
private String name;
public MyThread(Egg egg, String name) {
this.egg = egg;
this.name = name;
}
@Override
public void run() {
while (true) {
if ("mother".equals(name)) {
egg.put(name);
} else {
egg.eat(name);
}
}
}
}
class Egg {
private int eggNum = 0;
public synchronized void put(String name) {
while (eggNum > 0) {
try {
System.out.println(name + " 进入等待状态....");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggNum = eggNum + 1;
System.out.println(name + " 放了1个鸡蛋....");
this.notifyAll();
}
public synchronized void eat(String name) {
while (eggNum <= 0) {
try {
System.out.println(name + "进入等待状态....");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggNum--;
System.out.println(name + " 吃了一个鸡蛋.....");
this.notifyAll();
运行结果
用Lock及Condition修改 运行结果 mother 放了一个鸡蛋..... |