死锁

package t1;

public class TestThread4 {
private final Object lock1 = new Object();
private final Object lock2 = new Object();

public void instanceMethod1() {
synchronized (lock1) {
synchronized (lock2) {
System.out.println("first thread in instanceMethod1");
}
}
}

public void instanceMethod2() {
synchronized (lock2) {
synchronized (lock1) {
System.out.println("second thread in instanceMethod2");
}
}
}

public static void main(String[] args) {
TestThread4 testThread4 = new TestThread4();

Runnable r1 = new Runnable() {
public void run() {
while (true) {
testThread4.instanceMethod1();
try {
Thread.sleep(50);
} catch (Exception e) {
}
}
}
};
Thread th1 = new Thread(r1);
Runnable r2 = new Runnable() {

@Override
public void run() {
while (true) {
testThread4.instanceMethod2();
try {
Thread.sleep(50);
} catch (Exception e) {
}
}
}
};
Thread th2 = new Thread(r2);
th1.start();
th2.start();
}
}

 

结果:

 

posted @ 2020-03-30 17:33  工设091  阅读(97)  评论(0)    收藏  举报