【发布时间】:2016-05-06 08:29:37
【问题描述】:
我想在 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();
}
}
【问题讨论】:
-
我认为
competition应该是race condition...
标签: java multithreading reentrantlock