多執行緒(四)lock和Condition
阿新 • • 發佈:2018-12-11
lock類似於synchronized,拓展讀寫鎖,讀鎖之間不互斥,寫鎖之間互斥
Condition類似於執行緒技術中的wait和notify
使用lock和Condition能實現更多的特性
設計三個執行緒,第一個執行緒迴圈1次,第二個執行緒迴圈2次,第三個執行緒迴圈5次
接著第一個執行緒迴圈1次,第二個執行緒迴圈2次,第三個執行緒迴圈5次
如此迴圈50次
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionCommunication { public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable() { public void run() { for (int i = 1; i <= 50; i++) { business.sub2(i); } } }).start(); new Thread(new Runnable() { public void run() { for (int i = 1; i <= 50; i++) { business.sub3(i); } } }).start(); for (int i = 1; i <= 50; i++) { business.main(i); } } static class Business { Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); private int flag = 1; public void sub2(int i) { lock.lock(); try { while (flag!=2) { try { condition2.await(); } catch (Exception e) { e.printStackTrace(); } } for (int j = 1; j <= 2; j++) { System.out.println("sub2第" + j + "次迴圈,總迴圈:" + i); } flag = 3; condition3.signal(); } finally { lock.unlock(); } } public void sub3(int i) { lock.lock(); try { while (flag!=3) { try { condition3.await(); } catch (Exception e) { e.printStackTrace(); } } for (int j = 1; j <= 5; j++) { System.out.println("sub3第" + j + "次迴圈,總迴圈:" + i); } flag = 1; condition1.signal(); } finally { lock.unlock(); } } public void main(int i) { lock.lock(); try { while (flag!=1) { try { condition1.await(); } catch (Exception e) { e.printStackTrace(); } } for (int j = 1; j <= 1; j++) { System.out.println("sub1第" + j + "次迴圈,總迴圈:" + i); } flag = 2; condition2.signal(); } finally { lock.unlock(); } } } }