为了账号安全,请及时绑定邮箱和手机立即绑定

请问我这个死锁写的有什么问题吗?

请问我这个死锁写的有什么问题吗?

智慧大石 2019-02-26 23:45:20
看得视频,跟着敲了一遍,是想写个死锁,但是能执行成功,麻烦帮看看为什么? public class TestDeadLock implements Runnable { public int flag = 1; static Object o1 = new Object(); static Object o2 = new Object(); public void run () { System.out.println("flag=" + flag); if (flag == 1) { synchronized (o1) { try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } } synchronized (o2) { System.out.println(1); } } if (flag == 0) { synchronized (o2) { try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } synchronized (o1) { System.out.println(0); } } } } public static void main(String[] args) { TestDeadLock td1 = new TestDeadLock(); TestDeadLock td2 = new TestDeadLock(); td1.flag = 1; td2.flag = 0; Thread t1 = new Thread(td1); Thread t2 = new Thread(td2); t1.start(); t2.start(); } }
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

经过朋友指点,问题找到了
if (flag == 1) 这个逻辑里,o1与o2对象,没有产生依赖关系。

修改为后

public class TestDeadLock implements Runnable {
    public int flag = 1;
    static Object o1 = new Object();
    static Object o2 = new Object();

    public void run () {
        System.out.println("flag=" + flag);

        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                synchronized (o2) {
                       System.out.println(1);
                }
            }
        }

        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                synchronized (o1) {
                    System.out.println(0);
                }
            }
        }
    }

    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();

        td1.flag = 1;
        td2.flag = 0;

        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);

        t1.start();
        t2.start();
    }
}
查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 408 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信