打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
java 线程间通信

等待唤醒机制:

wait(),notify(),notifyAll()都使用在同步中,因为要对持有监视器(锁)的线程操作。

所以要使用在同步中,因为只有同步太具有锁。

定义在Object类中是因为这些方法在操作同步中线程时,都必须要标识他们所操作线程持有的锁,只有同一个锁上的被等待线程可以被同一个锁上的notify唤醒,可以对不同锁中的线程进行唤醒,等待和唤醒必须是同一个锁。

而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object中。

class Res {    private String name;    private String sex;    private boolean flag;    public synchronized void set(String name, String sex) {        if (flag) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.name = name;        this.sex = sex;        this.flag = true;        this.notify();    }    public synchronized void print() {        if (!flag) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(name + "......" + sex);        this.flag = false;        this.notify();    }}class Input implements Runnable {    private Res r;    public Input(Res r) {        this.r = r;    }    @Override    public void run() {        int x = 0;        while (true) {            if (x == 0) {                r.set("mike", "man");            } else {                r.set("丽丽", "女");            }            x = (x + 1) % 2;        }    }}class Output implements Runnable {    private Res r;    public Output(Res r) {        this.r = r;    }    @Override    public void run() {        while (true) {            r.print();        }    }}public class Demo {    public static void main(String[] args) {        Res r = new Res();        new Thread(new Input(r)).start();        new Thread(new Output(r)).start();    }}

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
wait notify (一)
黑马程序员ava学习笔记
Java多线程通信之wait()和notify()方法
Synchronized简介与原理
Java多线程之并发协作生产者消费者设计模式
JAVA多线程同步wait、notify、synchronized
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服