淺談java多線程wait,notify
更新時間:2019年05月29日 10:15:10 作者:lijingyulee
這篇文章主要介紹了java多線程wait,notify,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,下面小編和大家一起來學(xué)習(xí)一下吧
前言
1.因為涉及到對象鎖,Wait、Notify一定要在synchronized里面進行使用。
2.Wait必須暫定當(dāng)前正在執(zhí)行的線程,并釋放資源鎖,讓其他線程可以有機會運行
3.notify/notifyall: 喚醒線程
共享變量
public class ShareEntity {
private String name;
// 線程通訊標識
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(消費者)
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)文章
基于Java注解(Annotation)的自定義注解入門介紹
要深入學(xué)習(xí)注解,我們就必須能定義自己的注解,并使用注解,在定義自己的注解之前,我們就必須要了解Java為我們提供的元注解和相關(guān)定義注解的語法2013-04-04
Java二分查找算法與數(shù)組處理的應(yīng)用實例
二分查找法,又叫做折半查找法,它是一種效率較高的查找方法。數(shù)組對于每一門編程語言來說都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當(dāng)然不同語言對數(shù)組的實現(xiàn)及處理也不盡相同。Java 語言中提供的數(shù)組是用來存儲固定大小的同類型元素2022-07-07
SpringBoot+SpringCloud用戶信息微服務(wù)傳遞實現(xiàn)解析
這篇文章主要介紹了SpringBoot+SpringCloud實現(xiàn)登錄用戶信息在微服務(wù)之間的傳遞,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11

