代碼以下:code
public class SynchronizedAndLockDemo { public static void main(String[] args) throws InterruptedException { Writer writer = new Writer(); Thread t1 = new Thread(() -> { writer.testTryLock(); }); t1.setName("t1"); Thread t2 = new Thread(() -> { writer.testTryLock(); }); t2.setName("t2"); t1.start(); t2.start(); } } class Writer { Lock lock = new ReentrantLock(); public void testTryLock() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + ":" + lock.tryLock()); try { if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) { lock.lock(); System.out.println(threadName + " get the lock ..."); // Thread.sleep(2000); // System.out.println(threadName + " sleep 2s"); } else { System.out.println(threadName + " can't get the lock ..."); } } catch (Exception e) { } finally { if (lock.tryLock()) { lock.unlock(); System.out.println(threadName + " unlock"); } } } }
執行結果以下:get
t1:true t2:false t1 get the lock ... t1 unlock t2 can't get the lock ...
按理說,t1釋放鎖後 t2是在5秒內獲取不到鎖才終止,可是t1在5s內已經完成了任務,而且釋放了鎖,爲何t2仍然沒法得到鎖呢?是t1還沒有釋放鎖嗎?那lock.unlock()方法是未生效的嗎?百思不得其解
跪求大佬解惑it