#Java&面試--控制多執行緒安全與順序執行
阿新 • • 發佈:2018-12-10
Condition類的signal則是喚醒被Condition類使用await作用的那個執行緒,它會有針對性的喚醒執行緒,而不是隨機喚醒一個執行緒,以保證執行緒執行的順序:
package com.yzh.job.test; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Thread3 { public static void main(String[] args) { final G g = new G(); Thread t1 = new Thread(){ @Override public void run(){ String str = "Thread1"; g.show1(str); } }; Thread t2 = new Thread(){ @Override public void run(){ String str = "Thread2"; g.show2(str); } }; Thread t3 = new Thread(){ @Override public void run(){ String str = "Thread3"; g.show3(str); } }; t1.start(); t2.start(); t3.start(); } } class G{ //注意要寫在方法外面 Lock lock = new ReentrantLock(); //有幾個執行緒就定義幾個condition物件 Condition c1 = lock.newCondition(); Condition c2 = lock.newCondition(); Condition c3 = lock.newCondition(); int i = 3; public void show1(String str){ lock.lock(); if(i != 3){ try { c3.await();//相當於鎖住當前這一個執行緒,釋放鎖 } catch (Exception e) { e.printStackTrace(); } } for(int i = 0;i<1;i++){ System.out.println(str); } i = 2; //喚醒c2那一個作用的執行緒:指定執行緒喚醒 try { c2.signal(); } catch (Exception e) { e.printStackTrace(); } lock.unlock(); } public void show2(String str){ lock.lock(); if(i != 2){ try { c2.await();//相當於鎖住當前這一個執行緒,釋放鎖 } catch (Exception e) { e.printStackTrace(); } } for(int i = 0;i<2;i++){ System.out.println(str); } i = 1; //喚醒c1那一個作用的執行緒:指定執行緒喚醒 try { c1.signal(); } catch (Exception e) { e.printStackTrace(); } lock.unlock(); } public void show3(String str){ lock.lock(); if(i != 1){ try { //釋放當前鎖 c1.await();//相當於鎖住當前這一個執行緒,釋放鎖 } catch (InterruptedException e) { e.printStackTrace(); } } for(int i = 0;i<3;i++){ System.out.println(str); } i = 3; //喚醒c3那一個作用的執行緒:指定執行緒喚醒 try { c3.signal(); } catch (Exception e) { e.printStackTrace(); } lock.unlock(); } }