淺談java多線程wait,notify
前言
1.因?yàn)樯婕暗綄?duì)象鎖,Wait、Notify一定要在synchronized里面進(jìn)行使用。
2.Wait必須暫定當(dāng)前正在執(zhí)行的線程,并釋放資源鎖,讓其他線程可以有機(jī)會(huì)運(yùn)行
3.notify/notifyall: 喚醒線程
共享變量
public class ShareEntity {
private String name;
// 線程通訊標(biāo)識(shí)
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();
}
}
}
}
請(qǐng)求
@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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Java注解(Annotation)的自定義注解入門介紹
要深入學(xué)習(xí)注解,我們就必須能定義自己的注解,并使用注解,在定義自己的注解之前,我們就必須要了解Java為我們提供的元注解和相關(guān)定義注解的語(yǔ)法2013-04-04
Java二分查找算法與數(shù)組處理的應(yīng)用實(shí)例
二分查找法,又叫做折半查找法,它是一種效率較高的查找方法。數(shù)組對(duì)于每一門編程語(yǔ)言來(lái)說(shuō)都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當(dāng)然不同語(yǔ)言對(duì)數(shù)組的實(shí)現(xiàn)及處理也不盡相同。Java 語(yǔ)言中提供的數(shù)組是用來(lái)存儲(chǔ)固定大小的同類型元素2022-07-07
java騰訊AI人臉對(duì)比對(duì)接代碼實(shí)例
這篇文章主要介紹了java騰訊AI人臉對(duì)比對(duì)接,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
SpringBoot+SpringCloud用戶信息微服務(wù)傳遞實(shí)現(xiàn)解析
這篇文章主要介紹了SpringBoot+SpringCloud實(shí)現(xiàn)登錄用戶信息在微服務(wù)之間的傳遞,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11

