代码如下:
public class SynchronizedAndLockDemo {
public static void main(String[] args) throws InterruptedException {
Writer writer = new Writer();
Thread t1 = new Thread(() -> {
writer.testTryLock();
});
t1.setName("t1");
Thread t2 = new Thread(() -> {
writer.testTryLock();
});
t2.setName("t2");
t1.start();
t2.start();
}
}
class Writer {
Lock lock = new ReentrantLock();
public void testTryLock() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":" + lock.tryLock());
try {
if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {
lock.lock();
System.out.println(threadName + " get the lock ...");
// Thread.sleep(2000);
// System.out.println(threadName + " sleep 2s");
} else {
System.out.println(threadName + " can't get the lock ...");
}
} catch (Exception e) {
} finally {
if (lock.tryLock()) {
lock.unlock();
System.out.println(threadName + " unlock");
}
}
}
}
执行结果如下:
t1:true
t2:false
t1 get the lock ...
t1 unlock
t2 can't get the lock ...
按理说,t1释放锁后 t2是在5秒内获取不到锁才终止,但是t1在5s内已经完成了任务,并且释放了锁,为什么t2仍然无法获得锁呢?是t1尚未释放锁吗?那lock.unlock()方法是未生效的吗?百思不得其解
跪求大佬解惑
发表回复