1. 死锁
死锁指的是两个或以上的线程在执行过程中,因争夺资源而造成的一种互相等待的现象。
// 死锁代码
public class DeadLockDemo {
public static void main(String[] args) {
final Object objectA = new Object();
final Object objectB = new Object();
new Thread(()->{
synchronized (objectA) {
System.out.println("A get LockA and try to get LockB");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (objectB) {
System.out.println("A get LockB");
}
}
}, "A").start();
new Thread(()->{
synchronized (objectB) {
System.out.println("B get LockB and try to get LockA");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (objectA) {
System.out.println("B get LockA");
}
}
}, "B").start();
}
}
排查死锁代码:jstack pid