我想在Java線程中創建競爭條件併發並創建死鎖。 我使用ReentrantLock,但它不會拋出InterruptedException。爲什麼java ReentrantLock不拋出InterruptedException?
現在是死鎖,我使用lockInterruptibly,但它不會拋出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();
}
}
我覺得'比賽'應該是'比賽條件'... – Sayakiss