如何运用tryLock功能
最编程
2024-07-28 19:42:15
...
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
new Thread(() -> {
if (lock.tryLock()) {
System.out.println("A拿到锁了");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} else {
System.out.println("A没有拿到锁");
}
}, "MyThread-A").start();
new Thread(() -> {
if (lock.tryLock()) {
System.out.println("B拿到锁了");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} else {
System.out.println("B没有拿到锁");
}
}, "MyThread-B").start();
}