打开APP
userphoto
未登录

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

开通VIP
Java多线程通信之wait()和notify()方法

1.wait()方法和sleep()方法:

wait()方法在等待中释放锁;sleep()在等待的时候不会释放锁,抱着锁睡眠。

2.notify():

随机唤醒一个线程,将等待队列中的一个等待线程从等待队列中移到同步队列中。

public class Demo_Print {    public static void main(String[] args) {        Print p = new Print();        new Thread() {            public void run() {                while (true) {                    p.print1();                }            };        }.start();        new Thread() {            public void run() {                while (true) {                    p.print2();                }            };        }.start();    }}class Print {    int flag = 1;    public synchronized void print1() {        if (flag != 1) {            try {                this.wait();            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        System.out.print("你");        System.out.print("好");        System.out.print("吗????????????");        System.out.println();        flag = 2;        this.notify();    }    public synchronized void print2() {        if (flag != 2) {            try {                this.wait();            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        System.out.print("我");        System.out.print("好");        System.out.println();        flag = 1;        this.notify();    }}

在该案例中,实现一问一答的线程同步通信。当方法中开启了wait()方法后,通过改变flag的值来唤醒线程进而实行另一个方法。

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

联系客服