延續昨天介紹 ReentrantLock 的部份,今天要介紹如何使用 ReentrantLock 所提供的 newCondition() 方法。newCondition 類似於 wait 和 notify 的呼叫,它是使用 await 和 signal 的方式來呼叫。
以下的 Sample code 使用 ReentrantLock 的方式來建立 newCondition,做到等待和通知的效果:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class ReentrantLockThread1 implements Runnable {
private Lock lock;
private Condition condition;
public ReentrantLockThread1(Lock lock, Condition condition) {
this.lock = lock;
this.condition = condition;
}
@Override
public void run() {
try {
this.lock.lock();
System.out.println("RUN THREAD 1-1");
this.condition.await();
System.out.println("RUN THREAD 1-2");
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
this.lock.unlock();
}
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class ReentrantLockThread2 implements Runnable {
private Lock lock;
private Condition condition;
public ReentrantLockThread2(Lock lock, Condition condition) {
this.lock = lock;
this.condition = condition;
}
@Override
public void run() {
try {
this.lock.lock();
System.out.println("RUN THREAD 2");
this.condition.signal();
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
this.lock.unlock();
}
}
}
以上寫了二支 Thread 的程式,主要目的在於啟動 ReentrantLockThread1 執行緒之後會先印出 "RUN THREAD 1-1 字串之後,就會進行等待的動作,等到 ReentrantLockThread2 執行緒執行完成之後再讓 ReentrantLockThread1 把還沒執行完的部份執行完。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
public static void main(String args[]) {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
ReentrantLockThread1 t1 = new ReentrantLockThread1(lock, condition);
Thread thread1 = new Thread(t1);
thread1.start();
ReentrantLockThread2 t2 = new ReentrantLockThread2(lock, condition);
Thread thread2 = new Thread(t2);
thread2.start();
}
}
主程式主要會開啟二個執行緒, ReentrantLockThread1 和 ReentrantLockThread2。執行的結果如下:
RUN THREAD 1-1
RUN THREAD 2
RUN THREAD 1-2
從執行結果可以看出會先執行 ReentrantLockThread1 的 Thread 之後就會呼叫 await 方法等待的狀態,之後等到 ReentrantLockThread2 的 Thread 程式去呼叫 signal 方法,這樣 ReentrantLockThread1 的執行緒就會繼續執行把 RUN THREAD 1-2 的字串印出來。