1. 程式人生 > 實用技巧 >JUC學習:(wait,notify)--(await,signal)--(park,unpark)

JUC學習:(wait,notify)--(await,signal)--(park,unpark)

本文主要對Java.util.concurrent中鎖的相關對比學習。

他們分別是:

① Object中wait和notify;

② Lock中lock.newCondition:condition.await()和condition.signal();

③LockSupport中靜態方法park和unpark;

一、先上結論:

① 對於Object中wait和notify:必須在鎖中使用,這裡指synchronized,並且wait方法要先於notify,否則wait方法會一直阻塞該該執行緒。

② Lock中lock.newCondition:condition.await()和condition.signal():必須在鎖中使用,這裡指lock.lock()之後,並且await方法要先於singnal,否則await方法會一直阻塞該該執行緒。

③LockSupport優勢,優勢1:不需要再鎖中進行;優勢二:park方法可以不先於unpark方法。

二、測試程式碼

 1 public class LockAQS {
 2     private static Object objectLock = new Object();
 3     private static Lock lock = new ReentrantLock();
 4 
 5 
 6     public static void main(String[] args) {
 7 //        testWaitAndNotify();
 8 //        testLockAndUnLock();
9 testParkAndUnPark(); 10 } 11 12 static void testParkAndUnPark(){ 13 try { 14 TimeUnit.SECONDS.sleep(2); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 Thread t1 = new Thread(() -> { 19 System.out.println(Thread.currentThread().getName() + "\t" + "come in");
20 LockSupport.park(); 21 System.out.println(Thread.currentThread().getName() + "\t " + "被喚醒"); 22 }); 23 t1.start(); 24 25 new Thread(()->{ 26 System.out.println(Thread.currentThread().getName() + "\t " + "通知其他"); 27 LockSupport.unpark(t1); 28 }).start(); 29 30 } 31 32 static void testLockAndUnLock() { 33 Condition condition = lock.newCondition(); 34 new Thread(() -> { 35 try { 36 TimeUnit.SECONDS.sleep(2); 37 } catch (InterruptedException e) { 38 e.printStackTrace(); 39 } 40 try { 41 lock.lock(); 42 try { 43 System.out.println(Thread.currentThread().getName() + "\t" + " come in"); 44 condition.await(); 45 } catch (InterruptedException e) { 46 e.printStackTrace(); 47 } 48 System.out.println(Thread.currentThread().getName() + "\t " + "被喚醒"); 49 } finally { 50 lock.unlock(); 51 } 52 }, "LockA").start(); 53 54 new Thread(() -> { 55 try { 56 lock.lock(); 57 System.out.println(Thread.currentThread().getName() + "\t " + "通知其他"); 58 condition.signal(); 59 } finally { 60 lock.unlock(); 61 } 62 }, "LockB").start(); 63 } 64 65 static void testWaitAndNotify() { 66 new Thread(() -> { 67 try { 68 Thread.sleep(2000); 69 } catch (InterruptedException e) { 70 e.printStackTrace(); 71 } 72 synchronized (objectLock) { 73 System.out.println(Thread.currentThread().getName() + "\t" + "come in"); 74 try { 75 objectLock.wait(); 76 } catch (InterruptedException e) { 77 e.printStackTrace(); 78 } 79 System.out.println(Thread.currentThread().getName() + "\t " + "被喚醒"); 80 } 81 }, "A").start(); 82 83 new Thread(() -> { 84 synchronized (objectLock) { 85 System.out.println(Thread.currentThread().getName() + "\t" + "通知其他"); 86 objectLock.notify(); 87 } 88 }, "B").start(); 89 } 90 }