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();
}
}
使用lock.tryLock(),如果另一個線程持有鎖,那麼它將返回「假」,但它不應該能夠獲得鎖的另一個線程尚未解鎖 –
另外,你應該把'unlock()'放在'finally'塊中,以便JVM保證它被調用。 –
我無法理解的事情是,兩個線程如何能夠同時獲取鎖? –