JAVA之wait&notify&Condition

来源:互联网 发布:c语言中文网vip会员 编辑:程序博客网 时间:2024/05/16 10:37

         有某个线程唤醒等待中的线程,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;}@Overridepublic 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();

运行结果


xiaoming进入等待状态....
mother 放了1个鸡蛋....
mother 进入等待状态....
xiaoming 吃了一个鸡蛋.....

 

    用Lock及Condition修改

package thread;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;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;}@Overridepublic void run() {while (true) {if ("mother".equals(name)) {egg.put(name);} else {egg.eat(name);}}}}class Egg {private int eggNum = 0;    Lock lock=new ReentrantLock();    Condition condition=lock.newCondition();public  void put(String name) { lock.lock();try {while (eggNum > 0) {System.out.println(name + "进入等待状态....");condition.await();//这里要注意,不要选择wait(),wait()是Object中的}eggNum++;System.out.println(name + " 放了一个鸡蛋.....");condition.signalAll();} catch (Exception e) {e.printStackTrace();}finally{lock.unlock();}}public  void eat(String name) {   lock.lock();try {while (eggNum <= 0) {System.out.println(name + "进入等待状态....");condition.await();//这里要注意,不要选择wait(),wait()是Object中的}eggNum--;System.out.println(name + " 吃了一个鸡蛋.....");condition.signalAll();} catch (Exception e) {e.printStackTrace();}finally{lock.unlock();}}}

运行结果

mother 放了一个鸡蛋.....
mother进入等待状态....
xiaoming 吃了一个鸡蛋.....
mother 放了一个鸡蛋.....
mother进入等待状态....

    



 

原创粉丝点击