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

我自己写了一个线程死锁的程序,为什么锁不住

我自己写了一个线程死锁的程序,为什么锁不住

qq_之恩赫奥丶_0 2016-06-12 09:02:21
public class TextDead implements Runnable{public static void main(String[] args){ TextDead td1=new TextDead(); TextDead td2=new TextDead(); td1.flag=0; td2.flag=1; Thread t1=new Thread(td1); Thread t2=new Thread(td2); t1.start(); t2.start(); }int flag = 0;@Overridepublic void run() {if(flag==0){ try { TextDead.a(); TextDead.b(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }}if(flag==1){ try { TextDead.b(); TextDead.a(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}public static synchronized void a() throws InterruptedException{ Thread.sleep(10); System.out.println("SDFDSA");}public static synchronized void b() throws InterruptedException{ Thread.sleep(10); System.out.println(123);}}
查看完整描述

2 回答

?
wwpbjing

TA贡献20条经验 获得超5个赞

public class TextDead implements Runnable{

    int flag = 0;
    private static Object o1 = new Object();
    private static Object o2 = new Object();

    public static void main(String[] args){
        TextDead td1=new TextDead();
        TextDead td2=new TextDead();
        td1.flag=0;
        td2.flag=1;
        Thread t1=new Thread(td1);
        Thread t2=new Thread(td2);
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        if(flag==0){
            try {
                synchronized (o1) {
                    TextDead.a();
                    synchronized (o2) {
                        TextDead.b();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(flag==1){
            try {
                synchronized (o2) {
                    TextDead.b();
                    synchronized (o1) {
                        TextDead.a();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void a() throws InterruptedException{
        Thread.sleep(10);
        System.out.println("SDFDSA");
    }
    public static void b() throws InterruptedException{
        Thread.sleep(10);
        System.out.println(123);
    }
}


查看完整回答
反对 回复 2016-06-12
?
if_else_

TA贡献42条经验 获得超23个赞

你那个逻辑是不是有问题,你判断的是哪个Flag呢?

查看完整回答
反对 回复 2016-06-12
  • 2 回答
  • 1 关注
  • 1464 浏览

添加回答

举报

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