public class DeadLockDemo {
private static final String A = "A";
private static final String B = "B";
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (A) {
try {
Thread.sleep(1000);
System.out.println("Try to enter lock B");
synchronized (B) {
System.out.println("This is Thread A!!!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (B) {
try {
Thread.sleep(1000);
System.out.println("Try to enter lock A");
synchronized (A) {
System.out.println("This is Thread B!!!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
运行结果:
Try to enter lock A
Try to enter lock B