死锁DeadLock
死锁是指两个或两个以上的线程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。
public class Lock {
private static Object obj1 = new Object();
private static Object obj2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
try {
while (true) {
synchronized (obj1) {
System.out.println("lock obj1 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
synchronized (obj2) {
System.out.println("lock obj2 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
}
}
}
}
catch (Exception e) {
}
}
).start();
new Thread(() -> {
try {
while (true) {
synchronized (obj2) {
System.out.println("lock obj2 thread:" + Thread.currentThread().getName());
Thread.sleep(3000);
synchronized (obj1