死锁

死锁
形成死锁的条件
public class TestDeadLock extends Thread {

    //需要的资源用static保证只有一份
    private static Rice rice = new Rice();
    private static Water water = new Water();
    private int choice;
    private String name;

    public TestDeadLock(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {

        live();
    }
    //互相持有对方需要的资源的锁,需要拿到对方的资源
    public void live(){
        if (choice == 0) {
            synchronized (rice) { //获得米饭的锁
                try {
                    System.out.println(this.name + "获得米饭的锁");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (water) { //1秒后想获得水的锁
                    System.out.println(this.name + "获得水的锁");
                }
            }
        } else {
            synchronized (water) { //获得水的锁
                try {
                    System.out.println(this.name + "获得水的锁");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (rice) { //1秒后想获得米饭的锁
                    System.out.println(this.name + "获得米饭的锁");
                }
            }

        }
    }
    public static void main(String[] args) {
        TestDeadLock people1 = new TestDeadLock(0, "张三");
        TestDeadLock people2 = new TestDeadLock(1, "李四");
        people1.start();
        people2.start();

    }
}

class Rice {

}

class Water {

}


运行结果:


运行结果

程序卡在这里

避免死锁:

  public void live(){
        if (choice == 0) {
            synchronized (rice) { //获得米饭的锁
                try {
                    System.out.println(this.name + "获得米饭的锁");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (water) { //1秒后想获得水的锁
                System.out.println(this.name + "获得水的锁");
            }
        } else {
            synchronized (water) { //获得水的锁
                try {
                    System.out.println(this.name + "获得水的锁");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (rice) { //1秒后想获得米饭的锁
                System.out.println(this.name + "获得米饭的锁");
            }
        }
    }

先获得一个资源的锁。然后释放,然后再去获得另一个资源的锁。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容