ReentrantLock加鎖和釋放鎖的一般形式如下
Lock lock = new ReentrantLock();//默認(rèn)使用非公平鎖,如果要使用公平鎖,需要傳入?yún)?shù)true ........ lock.lock(); try { //更新對象的狀態(tài) //捕獲異常,必要時恢復(fù)到原來的不變約束 //如果有return語句,放在這里 finally { lock.unlock(); //鎖必須在finally塊中釋放 }ReentrantLock可以實現(xiàn)等待中斷,當(dāng)某現(xiàn)在等待時間過長,可以接受中斷退出等待,如下所示:
package jalonTest;import java.util.concurrent.locks.ReentrantLock; /* write線程一直占有鎖不退出,read線程在等待時收到中斷可以退出等待*/public class BufferInterruptibly { PRivate ReentrantLock lock = new ReentrantLock(); public void write() { lock.lock(); try { long startTime = System.currentTimeMillis(); System.out.println("開始往這個buff寫入數(shù)據(jù)…"); for (;;)// 模擬要處理很長時間 { if (System.currentTimeMillis() - startTime > Integer.MAX_VALUE) { break; } } System.out.println("終于寫完了"); } finally { lock.unlock(); } } public void read() throws InterruptedException { lock.lockInterruptibly();// 注意這里,可以響應(yīng)中斷 try { System.out.println("從這個buff讀數(shù)據(jù)"); } finally { lock.unlock(); } } public static void main(String args[]) { BufferInterruptibly buff = new BufferInterruptibly(); final Writer2 writer = new Writer2(buff); final Reader2 reader = new Reader2(buff); writer.start(); reader.start(); new Thread(new Runnable() { public void run() { long start = System.currentTimeMillis(); for (;;) { if (System.currentTimeMillis() - start > 5000) { System.out.println("不等了,嘗試中斷"); reader.interrupt(); //此處中斷讀操作 break; } } } }).start(); } } class Reader2 extends Thread { private BufferInterruptibly buff; public Reader2(BufferInterruptibly buff) { this.buff = buff; } @Override public void run() { try { buff.read();//可以收到中斷的異常,從而有效退出 } catch (InterruptedException e) { System.out.println("我不讀了"); } System.out.println("讀結(jié)束"); } } class Writer2 extends Thread { private BufferInterruptibly buff; public Writer2(BufferInterruptibly buff) { this.buff = buff; } @Override public void run() { buff.write(); } }前面提到的synchronized同步則不能實現(xiàn)中斷退出!
在synchronized同步文章中利用synchronized實現(xiàn)了類似的功能。synchronized和ReentrantLock最大的差別還是在于高并發(fā)性。ReentrantLock對高并發(fā)性效率較高!
新聞熱點(diǎn)
疑難解答