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); } }
添加回答
举报
0/150
提交
取消