怎么把这串代码搞成死锁?有什么办法吗?

public class TestDeadLock{ 
static Object O1 = new Object (); 
static Object O2 = new Object (); 
public static void main(String args[]){ 
Runner6 T1 = new Runner6(); 
Runner6 T2 = new Runner6(); 
T1.flag = false; 
T1.start(); 
T2.start(); 



class Runner6 extends Thread{ 
public boolean flag = true; 
public void run(){ 

if(flag){ 
synchronized(TestDeadLock.O1){ 
System.out.println("O1锁住了"); 
try{sleep(1000);}catch(InterruptedException e){} 

synchronized(TestDeadLock.O2){ 
System.out.println("2"); 


else{ 
synchronized(TestDeadLock.O2){ 
System.out.println("O2锁住了"); 
try{sleep(1000);}catch(InterruptedException e){ } 

synchronized(TestDeadLock.O1){ 
System.out.println("1"); 


     


白板的微信
浏览 324回答 2
2回答

繁星点点滴滴

最简单了 你把每个synchronized里面都加个相应的 TestDeadLock.O2.wait()或者TestDeadLock.O1.wait()就行了

眼眸繁星

给你一个例子:  package cn.com.io.threadDemo.ThreadSyn;    /**  * 通过两个属性值创建死锁  * 本程序通过两个线程各自锁定一个属性值,这样两个线程都无法结束,造成死锁  * @author Administrator  *  */  public class ThreadSyn2 implements Runnable{      private static Object obj1=new Object();      private static Object obj2=new Object();     /**   * @param args   */   public static void main(String[] args) {    ThreadSyn2 ts1=new ThreadSyn2();    ThreadSyn2 ts2=new ThreadSyn2();        Thread t1=new Thread(ts1);//线程1    Thread t2=new Thread(ts2);//线程2    t1.setName("theOne");    t2.setName("theTwo");        t1.start();    t2.start();     }     public void run() {    String name=Thread.currentThread().getName();    if(name.equals("theOne")){     method1(name);    }else{     method2(name);    }       }     //线程1的方法锁定obj1,线程2就无法完成   private void method1(String name) {    System.out.println(name);    synchronized(obj1){     try {      Thread.sleep(1000);     } catch (InterruptedException e) {      e.printStackTrace();     }     synchronized(obj2){      System.out.println(obj2);     }       }     }        //线程1的方法锁定obj2,线程1就无法完成   private void method2(String name) {    System.out.println(name);    synchronized(obj2){     try {      Thread.sleep(1000);     } catch (InterruptedException e) {      e.printStackTrace();     }     synchronized(obj1){      System.out.println(obj1);     }    }     }  }  
打开App,查看更多内容
随时随地看视频慕课网APP