之前總結了部分無鎖機制的多線程基礎,理想的狀態當然是利用無鎖同步解決多線程程式設計的問題。但是實際碰到的問題使得很多情 況下,我們不得不藉助鎖同步來保證安全執行緒。自從JDK5開始,有兩種機制來屏蔽代碼塊在並行訪問的幹擾,synchronized關鍵字已經介紹 過了部分內容,所以這次簡單的說說另一種鎖機制:ReentrantLock。
對於synchronized的缺點之前也簡單的說了一些,實際使用中比較煩擾的幾點是:a.只有一個"條件"與鎖相關聯,這對於大量並發線程 的情況是很難管理(等待和喚醒);b.多線程競爭一個鎖時,其餘未得到鎖的線程只能不停的嘗試獲得鎖,而不能中斷。這種情況對於大量的 競爭線程會造成效能的下降等後果。JDK5以後提供了ReentrantLock的同步機制對於前面提的兩種情況有相對的改善。下面我還是寫個小例 子分析一下:
Java代碼
import java.util.concurrent.locks.ReentrantLock;
/**
* @author: yanxuxin
* @date: 2010-1-4
*/
public class ReentrantLockSample {
public static void main(String[] args) {
testSynchronized();
testReentrantLock();
}
public static void testReentrantLock() {
final SampleSupport1 support = new SampleSupport1();
Thread first = new Thread(new Runnable() {
public void run() {
try {
support.doSomething();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread second = new Thread(new Runnable() {
public void run() {
try {
support.doSomething();
}
catch (InterruptedException e) {
System.out.println("Second Thread Interrupted without executing counter++,beacuse it waits a long time.");
}
}
});
executeTest(first, second);
}
public static void testSynchronized() {
final SampleSupport2 support2 = new SampleSupport2();
Runnable runnable = new Runnable() {
public void run() {
support2.doSomething();
}
};
Thread third = new Thread(runnable);
Thread fourth = new Thread(runnable);
executeTest(third, fourth);
}
/**
* Make thread a run faster than thread b,
* then thread b will be interruted after about 1s.
* @param a
* @param b
*/
public static void executeTest(Thread a, Thread b) {
a.start();
try {
Thread.sleep(100);
b.start(); // The main thread sleep 100ms, and then start the second thread.
Thread.sleep(1000);
// 1s later, the main thread decided not to allow the second thread wait any longer.
b.interrupt();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
abstract class SampleSupport {
protected int counter;
/**
* A simple countdown,it will stop after about 5s.
*/
public void startTheCountdown() {
long currentTime = System.currentTimeMillis();
for (;;) {
long diff = System.currentTimeMillis() - currentTime;
if (diff > 5000) {
break;
}
}
}
}
class SampleSupport1 extends SampleSupport {
private final ReentrantLock lock = new ReentrantLock();
public void doSomething() throws InterruptedException {
lock.lockInterruptibly(); // (1)
System.out.println(Thread.currentThread().getName() + " will execute counter++.");
startTheCountdown();
try {
counter++;
}
finally {
lock.unlock();
}
}
}
class SampleSupport2 extends SampleSupport {
public synchronized void doSomething() {
System.out.println(Thread.currentThread().getName() + " will execute counter++.");
startTheCountdown();
counter++;
}
}