public class Test_1死锁 {
public static void main(String[] args) {
Object obj1 = new Object();
Object obj2 = new Object();
//th1
Thread th1 = new Thread() {
@Override
public void run() {
String name = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
synchronized (obj1) {
System.out.println("th1" + name + "hello");
synchronized (obj2) {
System.out.println("th1" + name + "world");
}
}
}
}
};
//th2
Thread th2 = new Thread() {
@Override
public void run() {
String name = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
synchronized (obj2) {
System.out.println("th2" + name + "你好");
synchronized (obj1) {
System.out.println("th2" + name + "中国");
}
}
}
}
};
th1.start();
th2.start();
}
}