这是一个关于线程加锁和解锁的小程序,理想的输出结果是
kitty is running
kitty is running
kitty is running
kitty is running
doggy is running
doggy is running
doggy is running
doggy is running
但执行结果是无输出信息,在debug模式下看到的是整个程序都在wait状态,而不是对象dog1在wait状态,求大神解释~~public class th4_1{

public static void main(String[] args) throws InterruptedException {
cccc dog=new cccc("doggy");
cccc cat=new cccc("kitty");
Thread dog1 = new Thread(dog); 
Thread cat1 = new Thread(cat); 

synchronized(dog1){
try {
dog1.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cat1.start();
dog1.start();
dog1.notify();
}
}
}
public class cccc implements Runnable{
private String id;
public cccc(String str){
id=str;
}
public void run(){
for (int i = 0; i < 4; i++) {
try {
Thread.sleep((int)(1000*Math.random()));
}
catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println(id+" is running");

}
} }Java多线程

解决方案 »

  1.   

    mian进程进入dog1.wait()时一直锁住了,main都不走 还谈什么其它线程
      

  2.   

    我稍微改下你看看public static void main(String[] args) throws InterruptedException {
    cccc dog = new cccc("doggy");
    cccc cat = new cccc("kitty");
    Thread dog1 = new Thread(dog);
    Thread cat1 = new Thread(cat);
    cat1.start();
    dog1.start();
    }
    }class cccc implements Runnable {
    private String id; public cccc(String str) {
    id = str;
    } public void run() {
    synchronized (JavaSeTest.class) {
    for (int i = 0; i < 4; i++) {
    try {
    Thread.sleep((int) (1000 * Math.random()));
    } catch (InterruptedException e) {
    }
    System.out.println(id + " is running");
    }
    }
    }
      

  3.   

    public class JavaSeTest {
    public static void main(String[] args) throws InterruptedException {
    cccc dog = new cccc("doggy");
    cccc cat = new cccc("kitty");
    Thread dog1 = new Thread(dog);
    Thread cat1 = new Thread(cat);
    cat1.start();
    dog1.start();
    }
    }class cccc implements Runnable {
    private String id; public cccc(String str) {
    id = str;
    } public void run() {
    synchronized (JavaSeTest.class) {
    for (int i = 0; i < 4; i++) {
    try {
    Thread.sleep((int) (1000 * Math.random()));
    } catch (InterruptedException e) {
    }
    System.out.println(id + " is running");
    }
    }
    }
    }
      

  4.   

    感谢指导~~还有一个问题,就是dog1.wait()锁住的不是dog1这个线程吗?为什么会锁住mian这个线程?
      

  5.   

    main在等dog1醒,可是他永远不会醒,所以mian也就死在那了
      

  6.   

    先去找点 wait/notify 机制的资料了解下,被wait锁定的一定是当前线程,dog1这个对象只是充当了锁而已。然后有空看看这个:
    http://www.ticmy.com/?p=219