public class ThreadLockDeadlock {
public static Object object1 = new Object();
public static Object object2 = new Object();
public static void main(String[] args) {
new Thread(new Thread1()).start();
new Thread(new Thread2()).start();
}
private static class Thread1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (object1) {
try {
System.out.println("Thread1 拿到object1");
Thread.sleep(2000);
synchronized (object2) {
System.out.println("Thread1 拿到object2");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static class Thread2 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (object2) {
try {
System.out.println("Thread2拿到object2");
Thread.sleep(2000);
synchronized (object1) {
System.out.println("Thread2拿到object1");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}