java 線程通訊

來源:互聯網
上載者:User

標籤:latch   string   塊代碼   images   ace   down   ++   長度   線程通訊   

java 線程通訊使用
wait notify 配合synchronized 
當線程執行wait()時,會把當前的鎖釋放,然後讓出CPU,進入等待狀態。
當執行notify/notifyAll方法時,會喚醒一個處於等待該 對象鎖 的線程,然後繼續往下執行,直到執行完退出對象鎖鎖住的地區(synchronized修飾的代碼塊)後再釋放鎖。

如下代碼:

public class ThreadTest {

//聲明一個線程可視化的list集合
public static List<String> list = new ArrayList<>();

public static void main(String[] args) {
Object lock = new Object();

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
list.add("lenny");
System.out.println(Thread.currentThread().getName() + "往list增加了新項目");
if (list.size() == 5) {
lock.notify(); //通知lock掛起的線程 繼續執行 synchronized 塊代碼 執行完成後 釋放鎖
System.out.println("當前線程:" + Thread.currentThread().getName() + ",已經發出通知");
}
}
}
}
}, "t1");

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
if (list.size() != 5) {
try {
lock.wait(); //此處線程掛起 釋放lock
System.out.println("list長度"+list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("當前線程:" + Thread.currentThread().getName() + ",收到通知");
}
}
}, "t2");

t2.start();
t1.start();
}
}

啟動並執行結果:

 注意這裡t2線程先執行,t1線程後執行。如果t1線程先執行那麼t2擷取不到lock,t1 notify的時候 通知不到t2。

 這麼做有點弊端:不能做到即時的通知,要想做到通知發出,另外一個線程馬上收到通知,需要用到java.util.concurrent 的CountDownLatch

java 線程通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.