ReentrantLock提供一種無條件,可輪詢,定時以及可中斷的鎖,加鎖和解鎖都是顯式的。java
tryLock的時候,若是獲取不到鎖,就會當即返回,而不會一直等待,所以能夠經過輪詢來解決順序問題ide
public static void transfer(Account from, Account to, int cash) throws Exception { ReentrantLock fromLock = new ReentrantLock(); ReentrantLock toLock = new ReentrantLock(); while (true) { if (fromLock.tryLock()) { try { if (toLock.tryLock()) { try { // todo something } finally { toLock.unlock(); } } } finally { fromLock.unlock(); } } } }
public static void function() throws Exception { ReentrantLock lock = new ReentrantLock(); if (lock.tryLock(1, TimeUnit.SECONDS)) { try { // todo something } finally { lock.unlock(); } } else { return; } }
通常若是使用同步鎖的話,當發生死鎖狀況,是不能被其餘線程調度去中斷他。使用reentrantLock能夠支持中斷。就是在線程裏調用lockInterruptibly()方法,表明該鎖能夠響應中斷,而後在主線程去調用thread.interrupt()去中斷。性能
public static void main(String[] args) throws Exception { Thread thread = new MyThread(); thread.interrupt(); } public static class MyThread extends Thread { MyThread() {} @Override public void run() { ReentrantLock lock = new ReentrantLock(); try { lock.lockInterruptibly(); // 支持響應中斷 } catch (InterruptedException e) { // 中斷異常 } try { // todo } finally { lock.unlock(); } } }
在Java 1.5版本,reentrantlock和synchronized性能差距很大,而在1.6版本,synchonized優化不少,二者已經差距很小了,所以若是在synchronized能夠達到目的的狀況下,應該優先使用。優化