gpt4 book ai didi

java - 为什么java ReentrantLock不抛出InterruptedException?

转载 作者:行者123 更新时间:2023-12-02 03:38:59 24 4
gpt4 key购买 nike

我想在 Java 线程并发中创建竞争条件并创建死锁。 我使用ReentrantLock,但它不会抛出InterruptedException。

现在是死锁,我使用lockInterruptically,但它不会抛出InterruptedException,有人可以告诉我为什么吗?

  public class Test {

public static void main(String[] args) throws InterruptedException {

final Object o1 = new Object();
final Object o2 = new Object();

final ReentrantLock l1 = new ReentrantLock();
final ReentrantLock l2 = new ReentrantLock();

Thread t1 = new Thread() {
public void run() {
try {
l1.lockInterruptibly();
System.out.println("I am in t1 step 1 " + o1.toString());
Thread.sleep(1000);
l2.lock();
try {
System.out.println("I am in t1 step 2 " + o2.toString());
} finally {
l2.unlock();
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

Thread t2 = new Thread() {
public void run() {
try {
l2.lockInterruptibly();
System.out.println("I am in t2 step 1 " + o2.toString());
Thread.sleep(1000);
l1.lock();
try {
System.out.println("I am in t2 step 2 " + o1.toString());
} finally {
l1.unlock();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
};

t1.start();
t2.start();
Thread.sleep(2000);
t1.interrupt();
t2.interrupt();
t1.join();
t2.join();

}
}

最佳答案

您的问题是每个线程尝试获取两个锁。

                // Thread 1.
l1.lockInterruptibly();
// ....
l2.lock();


// Thread 2.
l2.lockInterruptibly();
// ....
l1.lock();

因此每个线程都会获取一个锁,然后尝试获取另一个线程已经持有的锁。这称为死锁。

您没有看到java.lang.InterruptedException,因为线程正在等待的锁(第二个)不是可中断锁。

解决这个问题:

                // Thread 1.
l1.lockInterruptibly();
// ....
l2.lockInterruptibly();


// Thread 2.
l2.lockInterruptibly();
// ....
l1.lockInterruptibly();

关于java - 为什么java ReentrantLock不抛出InterruptedException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com