一个简单的死锁案例:
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();
}
}
标签:Thread,synchronized,Object,System,死锁,&&,手写,out
From: https://www.cnblogs.com/chenyi502/p/17559396.html