Java多線程通信wait()和notify()代碼實(shí)例
1.wait()方法和sleep()方法:
wait()方法在等待中釋放鎖;sleep()在等待的時(shí)候不會(huì)釋放鎖,抱著鎖睡眠。
2.notify():
隨機(jī)喚醒一個(gè)線程,將等待隊(duì)列中的一個(gè)等待線程從等待隊(duì)列中移到同步隊(duì)列中。
代碼如下
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();
}
}
在該案例中,實(shí)現(xiàn)一問(wèn)一答的線程同步通信。當(dāng)方法中開(kāi)啟了wait()方法后,通過(guò)改變flag的值來(lái)喚醒線程進(jìn)而實(shí)行另一個(gè)方法。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java通過(guò)notify和wait實(shí)現(xiàn)線程間的通信功能
- 淺談線程通信wait,notify作用
- java使用wait和notify實(shí)現(xiàn)線程通信
- 淺談Java線程間通信之wait/notify
- Java線程通信之wait-notify通信方式詳解
- Java通過(guò)wait()和notifyAll()方法實(shí)現(xiàn)線程間通信
- Java多線程中的wait/notify通信模式實(shí)例詳解
- Java使用wait和notify實(shí)現(xiàn)線程之間的通信
- Java使用wait/notify實(shí)現(xiàn)線程間通信上篇
- 徹底理解Java線程通信wait / notify(原理 + 實(shí)戰(zhàn))
相關(guān)文章
Mybatis插件+注解實(shí)現(xiàn)數(shù)據(jù)脫敏方式
這篇文章主要介紹了Mybatis插件+注解實(shí)現(xiàn)數(shù)據(jù)脫敏方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
javaweb購(gòu)物車案列學(xué)習(xí)開(kāi)發(fā)
這篇文章主要為大家詳細(xì)介紹了javaweb購(gòu)物車案列學(xué)習(xí)開(kāi)發(fā)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
線程池ThreadPoolExecutor并行處理實(shí)現(xiàn)代碼
這篇文章主要介紹了線程池ThreadPoolExecutor并行處理實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
springMVC?@RestControllerAdvice注解使用方式
這篇文章主要介紹了springMVC?@RestControllerAdvice注解使用方式,下面通過(guò)一個(gè)簡(jiǎn)單的示例,演示如何使用?@RestControllerAdvice,感興趣的朋友跟隨小編一起看看吧2024-08-08
Springboot Cucumber測(cè)試配置介紹詳解
這篇文章主要介紹了Springboot Cucumber測(cè)試配置介紹詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
基于SpringBoot實(shí)現(xiàn)一個(gè)方法級(jí)耗時(shí)監(jiān)控器
本文介紹基于SpringBoot實(shí)現(xiàn)的輕量級(jí)耗時(shí)監(jiān)控器,通過(guò)AOP攔截方法并分級(jí)存儲(chǔ)數(shù)據(jù),提供可視化統(tǒng)計(jì)界面,支持調(diào)用次數(shù)、耗時(shí)、失敗次數(shù)分析及多維排序,適合中小型項(xiàng)目快速集成,無(wú)需復(fù)雜配置,需要的朋友可以參考下2025-09-09

