21 死锁


死锁,前提是资源唯一且被锁住 synchronized

package ThreadDemo;

// 死锁问题
public class Test21_DeadLock {
    public static void main(String[] args) {
        new Thread(new DeadLock(0),"a线程").start();
        new Thread(new DeadLock(1),"b线程").start();
    }
}

// A资源
class A{ }

// B 资源
class B{ }

// 死锁
class DeadLock implements Runnable{
    // 资源唯一才会引发死锁
    static A a=new A();
    static B b=new B();
    int choice;
    public DeadLock(int choice){
        this.choice=choice;
    }
    @Override
    public void run() {
        try {
            choice();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public void choice() throws InterruptedException {
        if (choice==0){
            synchronized (a){  // 先获得a,再获得b;等两个资源都拿到之后才释放
                System.out.println(Thread.currentThread().getName()+"获得了a资源");
                Thread.sleep(1000);  // 等待其他线程获得b,形成死锁
                synchronized (b){
                    System.out.println(Thread.currentThread().getName()+"获得了b资源");
                }
            }
        }else {
            synchronized (b){  // 先获得b,再获得a;等两个资源都拿到之后才释放
                System.out.println(Thread.currentThread().getName()+"获得了b资源");
                Thread.sleep(1000);  // 等待其他线程获得b,形成死锁
                synchronized (a){
                    System.out.println(Thread.currentThread().getName()+"获得了a资源");
                }
            }
        }
    }
}
posted @ 2023-09-07 22:02  被占用的小海海  阅读(8)  评论(0)    收藏  举报