关联static、synchronized
public class Test{
public static void main(String[] args){
DeadLock dl0 = new DeadLock();
DeadLock dl1 = new DeadLock();
dl0.flag = 0;
dl1.flag = 1;
Thread t0 = new Thread(dl0);
Thread t1 = new Thread(dl1);
t0.start();
t1.start();
}
}
class DeadLock implements Runnable{
static Object o1 = new Object();
static Object o2 = new Object();
public int flag = 1;
public void run(){
if(flag == 0 ){
synchronized(o1){
try{
Thread.sleep(500);
}catch(InterruptedException a){
System.out.println(a);
System.exit(-1);
}
synchronized(o2){
System.out.println("success");
}
}
}
if(flag == 1){
synchronized(o2){
try{
Thread.sleep(500);
}catch(InterruptedException a){
System.out.println(a);
System.exit(-1);
}
synchronized(o1){
System.out.println("success");
}
}
}
}
}
运行结果
//程序发生死锁
如果上述代码DeadLock类中的成员变量不加static修饰符
原来的:
static Object o1 = new Object();
static Object o2 = new Object();
不加static之后的:
Object o1 = new Object();
Object o2 = new Object();
运行结果:
success
success
原因如下:
不加static的时候内存中的情况
加了static之后