无法使用下一个代码重现死锁
我正在尝试使用下一个代码来解决死锁,但它似乎效果很好。
请看下面:
public class Deadlock {
static Object lock1 = new Object();
static Object lock2 = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (lock1) {
System.out.println("Thread 1: locked lock1");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1: locked lock2");
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (lock2) {
System.out.println("Thread 2: locked lock2");
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2: locked lock1");
}
}
}
}).start();
}
}
在这种情况下我不明白什么或这段代码有什么问题?