原因: 同时争夺同一资源导致死锁, 两个线程,彼此在等待对方占据的锁
Thread1
public class Thread1 extends Thread {
Object o1;
Object o2;
public Thread1(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o1){
System.out.println("进入线程 1 锁定对象 1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
System.out.println("进入线程 1 锁定对象 2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("进入线程 1 释放对象 2");
}
System.out.println("进入线程 1 释放对象 1");
}
}
}
Thread2
public class Thread2 extends Thread {
Object o1;
Object o2;
public Thread2(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o2){
System.out.println("进入线程 2 锁定对象 2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
System.out.println("进入线程 2 锁定对象 1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("进入线程 2 释放对象 1");
}
System.out.println("进入线程 2 释放对象 2");
}
}
}
测试
public class Main {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Thread1 thread1 = new Thread1(o1, o2);
Thread2 thread2 = new Thread2(o1, o2);
thread1.start();
thread2.start();
}
}
result.gif结果
网友评论