1. 程式人生 > >Java程式設計思想AttemptLocking執行結果和預期不一樣(使用顯示的Lock物件)

Java程式設計思想AttemptLocking執行結果和預期不一樣(使用顯示的Lock物件)

平臺: Windows7 32bit

JDK版本: 1.5.0_22,1.8.0_121

實測結果為:

tryLock(): true
tryLock(2, TimeUnit.SECONDS): true
tryLock(): true
tryLock(2, TimeUnit.SECONDS): true
acquired

和書中給的例子不一樣,從結果上看是main執行緒中Thread.yield()方法,並沒有給後臺執行緒執行機會,沒有獲得競爭鎖

將Thread.yield()方法替換為TimeUnit.MILLISECONDS.sleep(1);後即可實現預期效果

tryLock(): true
tryLock(2, TimeUnit.SECONDS): true
acquired
tryLock(): false
tryLock(2, TimeUnit.SECONDS): false