获取锁之后,线程应该休眠一段时间(在这种情况下为6000ms),防止另一个线程获取锁定。当我使用l1.lock()
方法时,它正常工作,但是当我&# 39; m使用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();
}
}
答案 0 :(得分: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