JAVA wait()和notifyAll()实现线程间通讯

本例是阅读Think in Java中相应章节后,自己实际写了一下自己的实现

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/*
假设一个学生,日出而作日落而息
*/
class Student
{
    private boolean Awake=false;
    public synchronized void wakeUp()
    {
        Awake=true;
        System.out.println("WakeUp!");
        notifyAll();    //notifyAll()写在这里!1.临界区 2.已经做了一些改变
    }
    public synchronized void sleep()
    {
        Awake=false;
        System.out.println("Sleep!");
        notifyAll();    //同上
    }
    public  synchronized void waitForSleep() throws InterruptedException {
        while(Awake!=false) wait(); //等待写在这里!1.临界区 2.等待外界改变的条件
    }
    public  synchronized void waitForAwake() throws InterruptedException{
        while(Awake!=true) wait();  //同上
    }
    public boolean isAwake() {
        return Awake;
    }
}
class SunRise implements Runnable
{//日出
    Student student=null;
    public SunRise(Student student)
    {
        this.student=student;
    }
    @Override public void run()
    {
        try {
            while (!Thread.interrupted()) {
                student.waitForSleep(); //先等待环境变化
                TimeUnit.MILLISECONDS.sleep(100);
                student.wakeUp();       //环境已变化,起床!
                System.out.println("End Awake");
            }

        }catch (InterruptedException e)
        {
            e.printStackTrace();
        }

    }
}
class SunFall implements Runnable
{
    Student student=null;
    public SunFall(Student student)
    {
        this.student=student;
    }
    @Override public void run()
    {
        try{
            while (!Thread.interrupted()) {
                student.waitForAwake(); //先等待环境变化
                TimeUnit.MILLISECONDS.sleep(100);
                student.sleep();        //环境已变化,睡觉!
                System.out.println("End Sleep");
            }

        }catch (InterruptedException e)
        {
            e.printStackTrace();
        }

    }
}
public class Main{
    public static void main(String[]args)
    {
        Student me=new Student();
        SunRise sunRise=new SunRise(me);
        SunFall sunFall=new SunFall(me);
        ExecutorService service= Executors.newCachedThreadPool();
        service.execute(sunRise);
        service.execute(sunFall); 
    }
}

 输出是

WakeUp!
End Awake
Sleep!
End Sleep

的不停循环。

应该算成功了吧。

posted @ 2018-01-21 00:27  我也想学编程  阅读(188)  评论(0编辑  收藏  举报