void lock(); //獲取鎖 void lockInterruptibly() throws InterruptedException; //獲取鎖,且當前線程可被中斷 boolean tryLock(); //嘗試獲取鎖,true獲取到鎖, false未獲取到鎖 boolean tryLock(long time, TimeUnit unit) throws InterruptedException; void unlock(); //釋放鎖 Condition newCondition(); //在當前鎖上建立一個等待條件
Lock lock = new ReentrantLock(); lock.lock(); try{ // to do sth. } finally{ lock.unlock(); //需要在finally中釋放鎖 }
public boolean transferMoney(Account fromAcct, Account toAcct, int amount, long timeout, TimeUnit unit){ long fixedDelay = getFixedDelayComponentNanos(timeout, unit); long randMod = getRandomDelayModulusNanos(timeout, unit); long stopTime = System.nanoTime() + unit.toNanos(timeout); while (true){ if (fromAcct.lock.tryLock()){ //若獲取到源帳戶鎖 try{ if (toAcct.lock.tryLock()){ //若獲取到目的帳戶鎖 try{ if (fromAcct.getBalance() < amount){ throw new RuntimeException("money.not.enough"); } else{ fromAcct.debit(amount); toAcct.credit(amount); return true; } } finally{ toAcct.lock.unlock(); } } } finally{ fromAcct.lock.unlock(); } } if (System.nanoTime() < stopTime){ return false; } try { Thread.sleep(fixedDelay + rand.nextLong()%randMod); } catch (InterruptedException e) { } } }你也能夠採用定時實現:
lock.tryLock(timeout, unit);
lock.lockInterruptibly(); try{ // maybe throws InterruptedException doSomething(); } finally{ lock.unlock(); }
//讀寫鎖容許同時多個線程讀, 或最多一個線程寫 public interface ReadWriteLock { Lock readLock(); Lock writeLock(); }
1. 釋放優先。當寫入鎖釋放後,應該優先選擇讀線程,寫線程,仍是最早發出請求的線程? java
2. 讀線程插隊。鎖由讀線程持有,寫線程再等待,再來一個讀線程,是繼續讓讀線程訪問,仍是讓寫線程訪問. 併發
3. 重入性。讀取鎖和寫入鎖是否可重入? dom
4. 降級。將寫入鎖降級爲讀取鎖。 高併發
5. 升級。將讀取鎖升級爲寫入鎖。 工具
/** * 讀寫鎖來包裝Map */ public class ReadWriteMap<K, V> { private final Map<K, V> map; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock r = lock.readLock(); private final Lock w = lock.writeLock(); public ReadWriteMap(Map<K, V> map){ this.map = map; } // 其餘寫操做... public V put(K key, V value){ w.lock(); //請求寫鎖 try{ return map.put(key, value); } finally{ w.unlock(); //勿忘 } } // 其餘讀操做... public V get(K key){ r.lock(); //請求讀鎖 try{ return map.get(key); } finally{ r.unlock(); //勿忘 } } }
不吝指正。 性能