public class ThreadLock implements Runnable{ static Object o1 = new Object();
static Object o2 = new Object();
int flag = 1; public void run (){
System.out.println("flag="+flag);
if(flag == 1)
{
synchronized(o1)
{
try{
Thread.sleep(10000);

}catch(InterruptedException e){e.printStackTrace();}
System.out.println("t1.o1");
}
synchronized(o2)
{
System.out.println("t1.o2");
}
}
if( flag ==  0)
{
synchronized(o2)
{
try{
Thread.sleep(10000);

}catch(InterruptedException e){e.printStackTrace();}
System.out.println("t2.o2");

}
synchronized(o1)
{
System.out.println("t2.o1");
}
}
} public static void main(String[] args) {
// TODO Auto-generated method stub

ThreadLock tl = new ThreadLock();
ThreadLock ty = new ThreadLock();
tl.flag = 1;
ty.flag = 0;
Thread t1 = new Thread(tl);
Thread t2 = new Thread(ty);

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

解决方案 »

  1.   

    一般 死锁 也不是保证每次都产生,
    把代码改了一下,估计可以发生public class ThreadLock implements Runnable { static Object o1 = new Object();
    static Object o2 = new Object();
    int flag = 1; public void run() {
    System.out.println("flag=" + flag);
    if (flag == 1) {
    for(int i=0;i<10;i++) {
    synchronized (o1) {
    try {
    Thread.sleep(100);
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("t1.o1"); synchronized (o2) {
    System.out.println("t1.o2");
    } }
    }
    }
    if (flag == 0) {
    for(int i=0;i<10;i++) {
    synchronized (o2) {
    try {
    Thread.sleep(100);
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("t2.o2"); synchronized (o1) {
    System.out.println("t2.o1");
    } }
    }
    }
    } public static void main(String[] args) {
    // TODO Auto-generated method stub ThreadLock tl = new ThreadLock();
    ThreadLock ty = new ThreadLock();
    tl.flag = 1;
    ty.flag = 0;
    Thread t1 = new Thread(tl);
    Thread t2 = new Thread(ty); t1.start();
    t2.start();
    }
    }
      

  2.   

    死锁完全可以通过sleep来强制造成...
       之所以没有出现死锁,肯定是死锁条件不具备.
          synchronized (o1) 与synchronized (o2)中代码块没有涉及到对象的互相堵塞.