日期:2014-05-20  浏览次数:20793 次

java 中多线程死锁问题
这个程序为什么不能实现死锁????????????




class Dead implements Runnable
{
private boolean flag;
Dead(boolean falg)
{
this.flag = flag;
}
public void run()
{
if (flag)
{
while (true)
{
synchronized(Locks.obj1)
{
System.out.println("if 1 启动!");
synchronized(Locks.obj2)
{
System.out.println("if 2 启动!");
}
}
}
}
else
{
while (true)
{
synchronized(Locks.obj2)
{
System.out.println("else 2 启动!");
synchronized(Locks.obj1)
{
System.out.println("else 1 启动!");
}
}
}
}
}

}

class Locks//定义锁对象
{
static Object obj1 = new Object();
static Object obj2 = new Object();
}

class DeadLock
{
public static void main(String[] args) 
{
Thread t1 = new Thread(new Dead(true));
Thread t2 = new Thread(new Dead(false));

t1.start();
t2.start();

}
}


------解决方案--------------------
找个视频看看吧,代码的问题还得自己去理解,梳理思路
------解决方案--------------------
因为Dead(flag)写错了

Java code

class Dead implements Runnable
{
    private boolean flag;
    
    Dead(boolean flag)    //你写成falg了
    {
        this.flag = flag;
    }
    
    public void run()
    {
        if (flag)
        {
            while (true)
            {
                synchronized(Locks.obj1)
                {
                    System.out.println("if 1 启动!");
                    synchronized(Locks.obj2)
                    {
                        System.out.println("if 2 启动!");
                    }
                }
            }
        }
        else
        {
            while (true)
            {
                synchronized(Locks.obj2)
                {
                    System.out.println("else 2 启动!");
                    synchronized(Locks.obj1)
                    {
                        System.out.println("else 1 启动!");
                    }
                }
            }
        }
    }

}

class Locks//定义锁对象
{
    static Object obj1 = new Object();
    static Object obj2 = new Object();
}

class DeadLock
{
    public static void main(String[] args) 
    {
        Thread t1 = new Thread(new Dead(true));
        Thread t2 = new Thread(new Dead(false));
        
        t1.start();
        t2.start();
    
    }
}

------解决方案--------------------
Dead(boolean falg)
{
this.flag = flag;
}

主要还是你不太小心了,这块有点小错误,应该都是flag。这样创建对象调用构造方法时值没有传就去,所以就是其boolean的默认值false。导致没法得到自己想要的结果,加油。
------解决方案--------------------
this.flag = flag;这里的flag都是指字段flag,逻辑上有问题,但语法上没问题