死锁产生的原因:
- 互斥条件:指线程对已经获取到的资源进行排它性使用,即该资源同时只由一个线程占用
- 请求并持有条件:只一个线程已经持有了至少一个资源,但又提出了新的资源请求,而新资源已经被其他线程占用,所以当前线程会被阻塞,但阻塞的同时不释放当前资源
- 不可剥夺条件:指线程获取到的资源在自己使用完之前不能被其他线程抢占,只有在自己使用完毕后才由自己释放该资源
- 环路等待条件
public static void main(String[] args) {
String a="A";
String b="B";
new Thread(()->{
synchronized (a){
try {
Thread.sleep(1);
}catch (InterruptedException e){
}
synchronized (b){
System.out.println("我是A");
}
}
}).start();
new Thread(()->{
synchronized (b){
synchronized (a){
System.out.println("我是b");
}
}
}).start();
}
提问:改动一处,让死锁释放资源?
解决方案:
public static void main(String[] args) {
String a="A";
String b="B";
new Thread(()->{
synchronized (a){
try {
a.wait(1);
}catch (InterruptedException e){
}
synchronized (b){
System.out.println("我是A");
}
}
}).start();
new Thread(()->{
synchronized (b){
synchronized (a){
System.out.println("我是b");
}
}
}).start();
}