日期:2014-05-20  浏览次数:20608 次

关于java多线程wait()和notify()的问题
这是一个关于线程加锁和解锁的小程序,理想的输出结果是
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 多线程

------解决方案--------------------
mian进程进入dog1.wait()时一直锁住了,main都不走 还谈什么其它线程
------解决方案--------------------
引用:
感谢指导~~还有一个问题,就是dog1.wait()锁住的不是dog1这个线程吗?为什么会锁住mian这个线程?


严重理解错误。。。