淺談java多線程wait,notify
前言
1.因為涉及到對象鎖,Wait、Notify一定要在synchronized里面進(jìn)行使用。
2.Wait必須暫定當(dāng)前正在執(zhí)行的線程,并釋放資源鎖,讓其他線程可以有機(jī)會運(yùn)行
3.notify/notifyall: 喚醒線程
共享變量
public class ShareEntity { private String name; // 線程通訊標(biāo)識 private Boolean flag = false; public ShareEntity() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getFlag() { return flag; } public void setFlag(Boolean flag) { this.flag = flag; } }
線程1(生產(chǎn)者)
public class CommunicationThread1 extends Thread{ private ShareEntity shareEntity; public CommunicationThread1(ShareEntity shareEntity) { this.shareEntity = shareEntity; } @Override public void run() { int num = 0; while (true) { synchronized (shareEntity) { if (shareEntity.getFlag()) { try { shareEntity.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (num % 2 == 0) shareEntity.setName("thread1-set-name-0"); else shareEntity.setName("thread1-set-name-1"); num++; shareEntity.setFlag(true); shareEntity.notify(); } } } }
線程2(消費(fèi)者)
public class CommunicationThread2 extends Thread{ private ShareEntity shareEntity; public CommunicationThread2(ShareEntity shareEntity) { this.shareEntity = shareEntity; } @Override public void run() { while (true) { synchronized (shareEntity) { if (!shareEntity.getFlag()) { try { shareEntity.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(shareEntity.getName()); shareEntity.setFlag(false); shareEntity.notify(); } } } }
請求
@RequestMapping("test-communication") public void testCommunication() { ShareEntity shareEntity = new ShareEntity(); CommunicationThread1 thread1 = new CommunicationThread1(shareEntity); CommunicationThread2 thread2 = new CommunicationThread2(shareEntity); thread1.start(); thread2.start(); }
結(jié)果
thread1-set-name-0 thread1-set-name-1 thread1-set-name-0 thread1-set-name-1 thread1-set-name-0 thread1-set-name-1 thread1-set-name-0
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解springboot使用異步注解@Async獲取執(zhí)行結(jié)果的坑
本文主要介紹了springboot使用異步注解@Async獲取執(zhí)行結(jié)果的坑,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08Java利用Socket實現(xiàn)網(wǎng)絡(luò)通信功能
在早期的網(wǎng)絡(luò)編程中,Socket是很常見的實現(xiàn)技術(shù)之一,比如早期的聊天室,就是基于這種技術(shù)進(jìn)行實現(xiàn)的,另外現(xiàn)在有些消息推送,也可以基于Socket實現(xiàn),本文小編給大家介紹了Java利用Socket實現(xiàn)網(wǎng)絡(luò)通信功能的示例,需要的朋友可以參考下2023-11-11@PathVariable和@RequestParam傳參為空問題及解決
這篇文章主要介紹了@PathVariable和@RequestParam傳參為空問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11Spring+Http請求+HttpClient實現(xiàn)傳參
這篇文章主要介紹了Spring+Http請求+HttpClient實現(xiàn)傳參,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03