死锁demo
package org.example;
public class Main {
private static Object resource1 = new Object();//资源 1
private static Object resource2 = new Object();//资源 2
public static void main(String[] args) {
new Thread(() -> {
synchronized (resource1) {
System.out.println(Thread.currentThread().getName() + " get resource1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " waiting get resource2");
synchronized (resource2) {
System.out.println(Thread.currentThread().getName() + " get resource2");
}
}
}, "线程 1").start();
new Thread(() -> {
synchronized (resource2) {
System.out.println(Thread.currentThread().getName() + " get resource2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " waiting get resource1");
synchronized (resource1) {
System.out.println(Thread.currentThread().getName() + " get resource1");
}
}
}, "线程 2").start();
}
}
解决死锁的方法
要解决这个死锁,需要:
- 统一锁的获取顺序:
// 两个线程都按相同顺序获取锁
synchronized (resource1) {
synchronized (resource2) {
// 业务逻辑
}
}
- 使用超时机制:
if (lock1.tryLock(1000, TimeUnit.MILLISECONDS)) {
try {
if (lock2.tryLock(1000, TimeUnit.MILLISECONDS)) {
// 业务逻辑
}
} finally {
lock1.unlock();
}
}