2016-07-22 100 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

我无法理解的事情是,两个线程如何能够同时获取锁? –