各位大大 我写了一个程序是测试线程的死锁 但是发现打印出的结果和实际有出入 以下是源代码
class MyThreadTest
{
public static void main(String[] args){
ThreadTest tt = new ThreadTest();
new Thread(tt).start();
new Thread(tt).start();
//new Thread(tt).start();
//new Thread(tt).start();
}
}class ThreadTest implements Runnable
{
int i = 100;
Object o = new Object();
public void run(){
while(true){
synchronized(o){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(this){
if(i>0){
System.out.println("同步块~~"+Thread.currentThread().getName()+"      "+i);
i--;
}
}
} test();
}
}
public synchronized void test(){
synchronized(o){
if(i>0){
try{
Thread.sleep(10);
System.out.println("同步方法~~"+Thread.currentThread().getName()+"      "+i);
i--;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}理论上来说应该直接就进入死锁了 什么也不会打印 但是实际上会有很多打印结果 而且多次执行发现发生死锁的位置都不相同 哪位大大能给解释一下啊

解决方案 »

  1.   

    原因很明显,是否发生死锁,取决于两个线程的执行速度,只有一个线程拿到o,另一个正好拿到this才会发生死锁,否则只是等待或执行.出现的几率由执行的时间片断决定的.
      

  2.   

    按3楼大大的说法把代码改了下 保证一个线程拿到o 另一个线程正好拿到this 不过仍然会打印一行结果 代码如下 class MyThreadTest
    {
    public static void main(String[] args){
    ThreadTest tt = new ThreadTest();
    new Thread(tt).start();
    try{
    Thread.sleep(1);
    }catch(Exception e){
    e.printStackTrace();
    }
    tt.b = true;
    new Thread(tt).start();
    //new Thread(tt).start();
    //new Thread(tt).start();
    }
    }class ThreadTest implements Runnable
    {
    int i = 100;
    boolean b = false;
    Object o = new Object();
    public void run(){
    if(b==true){
    test();
    }else{
    while(true){
    synchronized(o){
    try{
    Thread.sleep(10);
    }catch(Exception e){
    e.printStackTrace();
    }
    synchronized(this){
    if(i>0){
    System.out.println("同步块~~"+Thread.currentThread().getName()+"      "+i);
    i--;
    }
    }
    }
    }
    }
    }
    public synchronized void test(){
    synchronized(o){
    if(i>0){
    try{
    Thread.sleep(10);
    System.out.println("同步方法~~"+Thread.currentThread().getName()+"      "+i);
    i--;
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    }
    }
    }