死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。
public class DeadLockDemo {
static Book book1 = new Book();
static Book book2 = new Book();
public static void main(String[] args) {
new Thread(() -> {
try {
synchronized (book1) {
Thread.sleep(1000);
book2.getBook();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
synchronized (book2) {
Thread.sleep(1000);
book1.getBook();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
class Book {
public synchronized Book getBook() {
return new Book();
}
}