各位大大 下面是我写的测试死锁的代码 理论上来说应该直接进入死锁而不会打印任何东西 但是实际上总会有东西打印 憋了一天了 实在看不明白 哪位大大给解释一下为什么啊
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){//为true时将只会打印一行同步块语句 为false时将会打印不确定行数的同步方法语句
while(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();
}
}
}
}
}

解决方案 »

  1.   

    main函数所在的线程起完第一个线程进入睡眠,第一个线程进入睡眠时,main函数所在的线程起的第二个线程一定要等第一个线程再次进入睡眠才会运行?按这样的说法那么运行结果就说的通了 但是不明白为什么第二个线程一定要等第一个线程再次进入睡眠才能运行 按理说main函数所在的线程已经运行完毕 第一个线程又在睡眠 为什么第二个线程只能等待呢哪个大虾给说说啊 想不通啊
      

  2.   

    这里API和源码例子
    一个英文的,一个翻译的:
    http://apicode.gicp.net/class.do?api=selectByfatherIndex&father=255
    http://apicodecn.gicp.net/class.do?api=selectByfatherIndex&father=255