public class DeadLock implements Runnable
{
static Object o1 = new Object();
static Object o2 = new Object();
public int flag = 1;
public void run()
{
System.out.println("flag= " + flag);
if(flag == 1)
{
synchronized(o1)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized(o2)
{
System.out.println("1");
}
}
}
if(flag == 0)
{
synchronized(o2)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e )
{
e.printStackTrace();
} synchronized(o1)
{
System.out.println("0");
}
}
} } public static void main(String[] args)
{
DeadLock deadlock = new DeadLock();
DeadLock deadlock2 = new DeadLock();
deadlock.flag = 1;
deadlock.flag = 0;
Thread thread = new Thread(deadlock);
Thread thread2 = new Thread(deadlock2);
thread.start();
thread2.start();
}
}为什么Object o1,o2要声明为静态,而不用staic不会产生死锁?
{
static Object o1 = new Object();
static Object o2 = new Object();
public int flag = 1;
public void run()
{
System.out.println("flag= " + flag);
if(flag == 1)
{
synchronized(o1)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized(o2)
{
System.out.println("1");
}
}
}
if(flag == 0)
{
synchronized(o2)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e )
{
e.printStackTrace();
} synchronized(o1)
{
System.out.println("0");
}
}
} } public static void main(String[] args)
{
DeadLock deadlock = new DeadLock();
DeadLock deadlock2 = new DeadLock();
deadlock.flag = 1;
deadlock.flag = 0;
Thread thread = new Thread(deadlock);
Thread thread2 = new Thread(deadlock2);
thread.start();
thread2.start();
}
}为什么Object o1,o2要声明为静态,而不用staic不会产生死锁?
楼主如果想用非静态的方法,可以改一下代码,只用一个DeakLock对象。
public class DeadLock implements Runnable
{
Object o1 = new Object(); //改成非静态变量。
Object o2 = new Object();
public int flag = 1;
public void run()
{
System.out.println("flag= " + flag);
if(flag == 1)
{
synchronized(o1)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
} synchronized(o2)
{
System.out.println("1");
}
}
}
if(flag == 0)
{
synchronized(o2)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e )
{
e.printStackTrace();
}
synchronized(o1)
{
System.out.println("0");
}
}
}
} public static void main(String[] args)
{
DeadLock deadlock = new DeadLock(); //只产生一个DeadLock对象。
//DeadLock deadlock2 = new DeadLock();
//deadlock.flag = 1;
//deadlock.flag = 0;
Thread thread = new Thread(deadlock);
Thread thread2 = new Thread(deadlock);
thread.start(); //先启动一个线程,(主要是创造死锁的条件)。
try //另一线程延时启动,使flag变成0。
{
Thread.sleep(5);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
} deadlock.flag=0; //改变执行的位置。
thread2.start();
}
}