標籤:ide 線程 object tac main blog err 喚醒 對象
1 package test; 2 3 public class test1 { 4 5 public static void main(String[] args) { 6 7 new Thread(new thread1()).start(); 8 try { 9 Thread.sleep(5000);10 } catch (InterruptedException e) {11 12 e.printStackTrace();13 }14 new Thread(new thread2()).start();15 16 }17 }18 19 class thread1 implements Runnable {20 21 @Override22 public void run() {23 24 synchronized (test1.class) {25 System.out.println("here is thread1");26 System.out.println("thread1 is waiting");27 28 try {29 test1.class.wait();// 調用wait,會釋放線程鎖,進入等待鎖定池,直到調用notify方法喚醒,再次進入對象鎖定池準備擷取對象鎖進入運行狀態。30 31 } catch (InterruptedException e) {32 33 e.printStackTrace();34 }35 System.out.println("thread1 is going");36 System.out.println("thread1 is over");37 }38 }39 }40 41 class thread2 implements Runnable {42 43 @Override44 public void run() {45 //46 synchronized (test1.class) {47 System.out.println("here is thread2");48 System.out.println("thread2 is sleeping");49 test1.class.notify();50 try {51 Thread.sleep(4000);// 調用sleep,會等待相應時間,等待時線程鎖不釋放,時間到了會進入運行狀態;52 System.out.println("thread2 is going");53 System.out.println("thread2 is over");54 } catch (InterruptedException e) {55 e.printStackTrace();56 }57 }58 }59 }
運行結果:
here is thread1thread1 is waitinghere is thread2thread2 is sleepingthread2 is goingthread2 is overthread1 is goingthread1 is over
注釋掉49行的“test1.class.notify();”
程式會一直處於掛起狀態:
here is thread1thread1 is waitinghere is thread2thread2 is sleepingthread2 is goingthread2 is over
sleep()方法屬於Thread類;wait()方法屬於Object類。
在調用sleep()方法的過程中,線程不會釋放對象鎖。而當調用wait()方法的時候,線程會放棄對象鎖,進入等待此對象的等待鎖定池,只有針對此對象調用notify()方法後本線程才進入對象鎖定池準備。
感謝大神 Hongten;
sleep()與wait()的差別(java筆記-多線程)