以前使用wait()和notify()實現了循環打印字母和數字,而上篇博客講了ReentrantLock,所以,這篇博客講經過ReentrantLock來實現循環打印字母和數字,這裏咱們須要ReentrantLock與Condition搭配使用,ide
Condition主要方法爲await()方法和signal()方法,他們必須在lock()方法和unlock()方法之間使用。這兩個方法與Object的wait()方法和notify()方法做用同樣。仍是直接看代碼來分析把。spa
public static void main(String[] args) { final ReentrantLock lock = new ReentrantLock(true); final Condition charCondition = lock.newCondition(); final Condition numCondition = lock.newCondition(); new Thread(new Runnable() { @Override public void run() { List<String> list = Arrays.asList("A", "B", "C", "D", "E"); for (String str : list) { try { lock.lock(); System.out.println(str); numCondition.signal(); charCondition.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); for (Integer i : list) { try { lock.lock(); System.out.println(i); charCondition.signal(); numCondition.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }).start();
經過代碼看出,咱們聲明瞭一個ReentrantLock對象和兩個Condition。而後兩個線程中都經過lock()方法來索取鎖,而後打印各自的東西,而後喚醒另外一個線程,再將自身阻塞。代碼邏輯其實跟wait(),notify()的實現邏輯是同樣的。可是他們有一點很重要的區別:Condition能夠準確的喚醒指定的線程,而notify()沒法作到,他是由JVM控制的,咱們沒法決定。線程