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

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;

@Override

public 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);

}

}


qq_之恩赫奥丶_0
浏览 1469回答 2
2回答

wwpbjing

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);     } }

if_else_

你那个逻辑是不是有问题,你判断的是哪个Flag呢?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java