码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-21 01:09:46      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:改变   span   catch   err   end   except   boolean   cep   应该   

本例是阅读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

的不停循环。

应该算成功了吧。

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

标签:改变   span   catch   err   end   except   boolean   cep   应该   

原文地址:https://www.cnblogs.com/QEStack/p/8322457.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!