死锁的产生
1.图示
2.代码演示
线程1
public class Thread1 implements Runnable{
public Object A_lock;
public Object B_lock;
public Thread1(Object A_lock,Object B_lock) {
this.A_lock = A_lock;
this.B_lock = B_lock;
}
@Override
public void run() {
synchronized (A_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了A锁");
try {
Thread.sleep(100);
System.out.println("线程:" + Thread.currentThread().getName() + "正在获取B锁中");
synchronized (B_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了B锁");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
线程2
public class Thread2 implements Runnable{
public Object A_lock;
public Object B_lock;
public Thread2(Object A_lock,Object B_lock) {
this.A_lock = A_lock;
this.B_lock = B_lock;
}
@Override
public void run() {
synchronized (B_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了B锁");
System.out.println("线程:" + Thread.currentThread().getName() + "正在获取A锁中");
synchronized (A_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了A锁");
}
}
}
}
测试
public class test {
public static void main(String[] args) throws InterruptedException {
Object A_lock = new Object();
Object B_lock = new Object();
Thread1 thread1 = new Thread1(A_lock, B_lock);
Thread2 thread2 = new Thread2(A_lock, B_lock);
new Thread(thread1,"1").start();
Thread.sleep(5);
new Thread(thread2,"2").start();
}
}
运行结果:
解决死锁
public class Thread1 implements Runnable{
public Object A_lock;
public Object B_lock;
public Thread1(Object A_lock,Object B_lock) {
this.A_lock = A_lock;
this.B_lock = B_lock;
}
@Override
public void run() {
synchronized (A_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了A锁");
try {
Thread.sleep(100);
System.out.println("线程:" + Thread.currentThread().getName() + "正在获取B锁中");
synchronized (B_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了B锁");
B_lock.notify();
System.out.println("线程:" + Thread.currentThread().getName() + "唤醒了等待B锁的线程");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Thread2 implements Runnable{
public Object A_lock;
public Object B_lock;
public Thread2(Object A_lock,Object B_lock) {
this.A_lock = A_lock;
this.B_lock = B_lock;
}
@Override
public void run() {
synchronized (B_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了B锁");
try {
System.out.println("线程:" + Thread.currentThread().getName() + "让出了B锁,等待被唤醒");
B_lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程:" + Thread.currentThread().getName() + "正在获取A锁中");
synchronized (A_lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "获取了A锁");
}
}
}
}
运行结果