接上一篇文章,https://www.cnblogs.com/liumy/p/11633065.html
wait方法是讓當前線程等待,這里的當前線程不是指t,而是主線程。 wait會釋放鎖,等到其他線程調用notify方法時再繼續運行。
可以看下面的例子。
1 package com.citi.test.mutiplethread.demo0503; 2 3 import java.util.Date; 4 5 public class WaitTest { 6 public static void main(String[] args) { 7 ThreadA t1=new ThreadA("t1"); 8 System.out.println("t1:"+t1); 9 synchronized (t1) { 10 try { 11 //啟動線程 12 System.out.println(Thread.currentThread().getName()+" start t1"); 13 t1.start(); 14 //主線程等待t1通過notify喚醒。 15 System.out.println(Thread.currentThread().getName()+" wait()"+ new Date()); 16 t1.wait();// 不是使t1線程等待,而是當前執行wait的線程等待 17 System.out.println(Thread.currentThread().getName()+" continue"+ new Date()); 18 } catch (Exception e) { 19 e.printStackTrace(); 20 } 21 } 22 } 23 } 24 25 class ThreadA extends Thread{ 26 public ThreadA(String name) { 27 super(name); 28 } 29 @Override 30 public void run() { 31 synchronized (this) { 32 System.out.println("this:"+this); 33 try { 34 Thread.sleep(2000);//使當前線程阻塞1秒 35 } catch (InterruptedException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } 39 System.out.println(Thread.currentThread().getName()+" call notify()"); 40 this.notify(); 41 } 42 } 43 }
下面是執行結果。
可以看到synchronized(this),和synchronized(t1), 鎖的是同一個對象。
這個程序有兩個線程,一個是主線程main,一個是線程t1,所以會有鎖的競爭,因為是main方法先運行到第9行,所以先獲取到鎖。
這樣就導致了32行到40行的代碼必須在main主線程釋放鎖的時候才運行,而t1.await()就釋放了鎖,所以我們看執行結果。
32行在15行之后執行。
17行會等待t1線程執行完畢調用notify之后再執行。
這里就說明了,
在代碼中t1.await(),是讓運行這行代碼的線程等待,而不是讓t1這個線程等待。
參考資料:
https://www.jianshu.com/p/def7f016dd5e