死锁的问题

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

    }
}   

怎么把这串代码搞成死锁?

3个回答

[code="java"]

给个采纳!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

[/code]

[code="java"]

给你一个例子:

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

    }
    }

[/code]

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐