public class TestDeadLock implements Runnable{
static Object o1 = new Object();
static Object o2 = new Object();
int flag = 1;
public static void main(String[] args){

TestDeadLock test1 = new TestDeadLock();
TestDeadLock test2 = new TestDeadLock();
test1.flag = 0;
test2.flag = 1;
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.start();
t2.start();
}

public void run(){

if(flag == 0){
System.out.println("000000");
synchronized(o1){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("??????????????");
}
synchronized(o2){
System.out.println("111111111");
}
}


}

if(flag == 1){
System.out.println("111111");
synchronized(o2){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("??????????????");
}
synchronized(o1){
System.out.println("22222");
}
}

}
}
}如上,当程序的Object两个对象不为static类型时,不能形成死锁机制..这是怎么回事??

解决方案 »

  1.   

    不为static那么 每 new 一个 TestDeadLock 都会 new 出两个Object
    那么总共就有 4 个 Object 和 两个 TestDeadLock 对象
      

  2.   

    马士兵 。  因为不加static 的话 t1和t2的o1和o2是不同的,当然不存在资源的冲突了,因为不共享,加static所有对象共享,
      

  3.   

    不用static 的话  test1 的 o1 与 test2的o1 是不一样的(o2同理)   所以锁不住,当然不会发生死锁了。
      

  4.   

    楼主java基础有待加强,我去面试你,你肯定不会通过。
      

  5.   

    用static时, test1 的 o1 与 test2的o1 是指向同一对象,加锁是针对同一个对象
    不用static 的话  test1 的 o1 与 test2的o1 是不同对象,加锁是针对各自的对象