博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA wait()和notifyAll()实现线程间通讯
阅读量:4520 次
发布时间:2019-06-08

本文共 2318 字,大约阅读时间需要 7 分钟。

本例是阅读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 AwakeSleep!End Sleep

的不停循环。

应该算成功了吧。

转载于:https://www.cnblogs.com/QEStack/p/8322457.html

你可能感兴趣的文章
软件工程第一次作业
查看>>
【Android 界面效果24】Intent和PendingIntent的区别
查看>>
node学习之搭建服务器并加装静态资源
查看>>
android 按menu键解锁功能的开关
查看>>
wpf 自定义窗口,最大化时覆盖任务栏解决方案
查看>>
Linux 下的dd命令使用详解
查看>>
POJ-1273 Drainage Ditches 最大流Dinic
查看>>
ASP.NET学习记录点滴
查看>>
uva 12097(二分)
查看>>
[Noip2016] 愤怒的小鸟
查看>>
Linux系统基础管理
查看>>
JAVA wait()和notifyAll()实现线程间通讯
查看>>
python全栈脱产第11天------装饰器
查看>>
koa2 从入门到进阶之路 (一)
查看>>
Java / Android 基于Http的多线程下载的实现
查看>>
求职历程-----我的简历
查看>>
[总结]数据结构(板子)
查看>>
网页图片加载失败,用默认图片替换
查看>>
C# 笔记
查看>>
android 之输入法
查看>>