前言
成都創(chuàng)新互聯(lián)公司主要從事成都網(wǎng)站設計、成都網(wǎng)站建設、網(wǎng)頁設計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務。立足成都服務大城,十余年網(wǎng)站建設經(jīng)驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:18980820575
1.因為涉及到對象鎖,Wait、Notify一定要在synchronized里面進行使用。
2.Wait必須暫定當前正在執(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(生產者)
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(); }
結果
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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。