2016-07-22 138 views
0

獲得鎖定後,線程應該休眠一段時間(在這種情況下爲6000ms),以防止另一個線程獲取鎖定。當我使用l1.lock()方法時,它正常工作,但當我使用l1.tryLock()l1.tryLock(1000,TimeUnit.MILLISECOND)時,線程正在獲取鎖定,之前線程釋放鎖定。它可能如何?所有線程都鎖定?

import java.util.concurrent.locks.*; 
import java.util.concurrent.locks.Lock; 

class MyLocks implements Runnable { 
    static Lock l1; 

    public static void main(String... asd) { 
    l1 = new ReentrantLock(); 
    MyLocks obj = new MyLocks(); 
    new Thread(obj).start(); 
    new Thread(obj).start(); 
    } 

    public void run() { 
    System.out.println(Thread.currentThread().getName() + " is try to acquire lock"); 
    try { 
     l1.trylock(); 
    // only those thread which has acquired lock will get here. 
     System.out.println(Thread.currentThread().getName() + " has acquired lock"); 

     Thread.sleep(6000); 

    } catch (Exception e) { 
    } 
    l1.unlock(); 
    } 
} 

回答

2

一個常見的錯誤是調用方法而忽略結果。最有可能你正在運行

lock.tryLock(); // notice this ignores whether the lock was obtained or not. 

時,你應該做一些像

while(!lock.tryLock(1, TimeUnit.SECOND)) { 
    System.out.println(Thread.currentThread().getName()+" - Couldn't get lock, waiting"); 
} 

注:除非你是非常有信心,他們不事不要丟棄例外。

}catch(Exception e){} // something when wrong but lets pretend it didn't 

有關如何處理異常的一些提示。

https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html

+0

使用lock.tryLock(),如果另一個線程持有鎖,那麼它將返回「假」,但它不應該能夠獲得鎖的另一個線程尚未解鎖 –

+1

另外,你應該把'unlock()'放在'finally'塊中,以便JVM保證它被調用。 –

+0

我無法理解的事情是,兩個線程如何能夠同時獲取鎖? –