看操作系统想到之前面试的时候会经常被问到多线程的问题,也会经常被面试官要求写一个死锁,然后就想到了这个最简单的死锁,记录一下。
/**
* 写一个死锁
*/
public class demo01 {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Thread thread01 = new Thread(() -> {
synchronized (o2) {
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("A-ok");
}
}
},"A");
Thread thread02 = new Thread(() -> {
synchronized (o1) {
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("B-ok");
}
}
},"A");
thread01.start();
thread02.start();
}
}