public class Test2 implements Runnable {
private int t = 1;
private static Object o1 = new Object(), o2 = new Object();
public void run() {
if (t == 1) {
/* while (true)*/
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "获得了lock1锁");
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "获得了lock2锁");
}
}
} else {
/* while (true)*/
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "获得了lock2锁");
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "获得了lock1锁");
}
}
}
}
public static void main(String[] args){
Test2 t1 = new Test2();
Test2 t2 = new Test2();
t1.t = 1;
t2.t = 2;
new Thread(t1).start();
new Thread(t2).start();
}
}
死锁实例!终于调试好了!
最新推荐文章于 2025-03-11 19:00:36 发布