Lock
主要有4個方法:lock()、tryLock()、tryLock(long time, TimeUnit unit)和lockInterruptibly()。注意Lock不像synchronized一樣在異常時自動釋放鎖,因此需要在finally中解鎖——unlock()。
- lock()
該方法不能被中斷,一旦陷入死鎖就會陷入永久等待。 - tryLock()
用來嘗試獲取鎖,如當前鎖沒有被其他線程佔用,則獲取成功返回true,否則返回false代表獲取鎖失敗。 - tryLock(long time, TimeUnit unit)
同上,區別就在於設置超時時間。
/**
* 用tryLock()方法避免死鎖
*/
public class ReentrantLockByTryLock implements Runnable {
private static final Lock reentrantLock1 = new