標籤:logs buffer finally 代碼 rac art lin ant edit
轉載請註明原文地址:http://www.cnblogs.com/ygj0930/p/6556925.html
一:syncrhoized使用同一把鎖的多個線程用通訊實現執行順序的調度
我們知道,使用syncrhoized關鍵字修飾一個代碼塊、一個方式時,在代碼塊、方法執行完畢之前是不會釋放掉所持有的鎖的,在執行期間,其他申請這個鎖的線程只能阻塞等待。這些等待的線程被安排在一個等待隊列中。
現在,由於某種原因,在當前同步代碼塊A中需要另一個同步代碼塊B先執行完,然後A才能繼續進行下去。而同步代碼塊B是另一個線程來執行的,並且申請的是同一個同步鎖。此時,就需要在A中把鎖讓出去,並且讓A線程掛起(即讓出CPU,進入等待隊列)【通過wait()方法掛起線程,進入該同步鎖的等待隊列】。B在獲得同步鎖並且執行完後,則通過 notify()/notifyAll() 方法喚醒該同步鎖的等待隊列中的線程。A被喚醒後就由等待隊列中彈出,進入就緒態,等待擷取CPU使用權繼續執行。
二:ReentrantLock加鎖的線程之間的通訊實現執行調度
ReentrantLock加鎖的線程是通過Condition對象的await()、signal()/signalAll()方法來掛起當前線程(掛起前先調用lock.unlock()釋放掉鎖),喚醒相應線程(在某condition條件下等待的線程)先執行來實現的。
Condition的最大改進在於:更加精確地進行調度。當前線程可以顯式定義在某處“因何情況而等待”,也可以在釋放鎖後某處顯式地通知“因何情況而等待的線程可以啟動繼續執行了”。而不再是籠統地申請同一把鎖的等待線程全部啟動。
我們來看一下官方提供的例子:
package locks;import java.util.Random;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class AppOfficial { /** * BoundedBuffer 是一個定長100的集合,當集合中沒有元素,take方法需要等待,直到有元素時才返回元素 * 當集合滿了,要等待直到元素被take之後才執行put的操作 */ static class BoundedBuffer { //定義一個鎖對象 final Lock lock = new ReentrantLock(); //定義兩種被喚醒的條件:非滿、非空 final Condition notFull = lock.newCondition(); final Condition notEmpty = lock.newCondition(); final Object[] items = new Object[100]; int putptr, takeptr, count; public void put(Object x) throws InterruptedException { System .out.println("put wait lock"); //加鎖進行put操作 lock.lock(); System.out.println("put get lock"); try { //當集合滿了,則等待 非滿 情況的發生 while (count == items.length) { System.out.println("buffer full, please wait");
//在 非滿 條件下掛起,等待非滿條件的喚醒操作才繼續執行下去 notFull.await(); } items[putptr] = x; if (++putptr == items.length) putptr = 0; ++count; //執行完插入操作後,集合非空,通知 非空 條件下掛起的線程 可以繼續進行take操作了 notEmpty.signal(); } finally { lock.unlock(); } } public Object take() throws InterruptedException { System.out.println("take wait lock"); lock.lock(); System.out.println("take get lock"); try { while (count == 0) { System.out.println("no elements, please wait");
//在 非空 條件下掛起 notEmpty.await(); } Object x = items[takeptr]; if (++takeptr == items.length) takeptr = 0; --count; //集合不是滿的了,喚醒在 非滿 情況下掛起的put線程可以繼續執行put操作 notFull.signal(); return x; } finally { lock.unlock(); } } } public static void main(String[] args) { final BoundedBuffer boundedBuffer = new BoundedBuffer(); Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("t1 run"); for (int i=0;i<1000;i++) { try { System.out.println("putting.."); boundedBuffer.put(Integer.valueOf(i)); } catch (InterruptedException e) { e.printStackTrace(); } } } }) ; Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i=0;i<1000;i++) { try { Object val = boundedBuffer.take(); System.out.println(val); } catch (InterruptedException e) { e.printStackTrace(); } } } }) ; t1.start(); t2.start(); }}
【Java多線程通訊】syncrhoized下wait()/notify()與ReentrantLock下condition的用法比較