手写死锁&&死锁的原因是什么?如何快速定位死锁?如何避免死锁
一个简单的死锁案例:
package mylock;
public class DeadlockExample {
public static void main(String[] args) {
final Object resource1 = new Object();
final Object resource2 = new Object();
// 线程1占用资源1,等待资源2
Thread thread1 = new Thread(() -> {
synchronized (resource1){
System.out.println("Thread 1: 持有资源 1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource2){
System.out.println("Thread 1: 持有资源 2");
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (resource2){
System.out.println("Thread 2: 持有资源 2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource1){
System.out.println("Thread 2: 持有资源 1");
}
}
});
thread1.start();
thread2.start();
}
}

浙公网安备 33010602011771号