多线程的wait和nofify方法的使用

阅读: 评论:0

多线程的wait和nofify方法的使用

多线程的wait和nofify方法的使用

wait():让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)

notify()和notifyAll():则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。

wait(long timeout): 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)

wait和notify实现线程间通信:

资源类:

public class Text {//内容public String content;//读写标记:true,可以读,false,可以写public boolean flag;//数字public int num;
}

读数据线程类:

public class ReadThread extends Thread {private Text text;public ReadThread(Text text) { = text;}@SneakyThrows@Overridepublic void run() {while (true) {synchronized (text) {if (text.flag) {Thread.sleep(2000);System.out.println("读到的内容为:" + t);text.flag = false;System.out.println("=============读取内容结束=============");ify();}else{text.wait();}}}}
}

写入线程实现类:

public class WriteThread extends Thread {private Text text;public WriteThread(Text text) { = text;}@SneakyThrows@Overridepublic void run() {while (true) {synchronized (text) {if (!text.flag) {Thread.sleep(2000);String name = "";if (text.num % 2 == 0) {name = "小则";} else {name = "小明";}text.num = text.num + t = name;text.flag = true;System.out.println("-------写入内容结束---------");ify();} else {text.wait();}}}}
}

线程启动类:

 public static void main(String[] args) throws InterruptedException {Text text = new Text();ReadThread readThread = new ReadThread(text);WriteThread writeThread = new WriteThread(text);writeThread.start();Thread.sleep(1000);readThread.start();}

本文发布于:2024-01-29 03:28:44,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170647012912388.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:多线程   方法   wait   nofify
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23