死锁:是指有两个或者多个线程互相持有对方需要的资源,导致涉及到的所有线程都处于阻塞状态,无法继续运行。
import java.util.ArrayList;
import java.util.List;
public class DeadTest {
private static List<String> l1 = new ArrayList<>();
private static List<String> l2 = new ArrayList<>();
public static void main(String[] args) {
// Thread1
new Thread(()->{
try {
System.out.println("Thread1 starting.....");
while(true){
synchronized(DeadTest.l1){
System.out.println("Thread1 获取了 l1的锁");
Thread.sleep(1000);
System.out.println("Thread1 想获取 l2的锁");
synchronized(DeadTest.l2){
System.out.println("Thread1 拿到了l2的锁");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
// Thread1
new Thread(()->{
try {
System.out.println("Thread2 starting.....");
while(true){
synchronized(DeadTest.l2){
System.out.println("Thread2 获取了 l2的锁");
Thread.sleep(1000);
System.out.println("Thread2 想获取 l1的锁");
synchronized(DeadTest.l1){
System.out.println("Thread2 拿到了l1的锁");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
运行结果如下:Thread1永远拿不到l2的锁,Thread2永远拿不到l1的锁,就产生了死锁