为了提问方便,写了一段程序,不明白为什么notify不能唤醒wait。预期输出应该是不停的输出1,为什么只输出一个1,然后就不动了?
class Test implements Runnable { public void run() {
try {
while (true) {
System.out.print(1);
synchronized (this) {
wait();
notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}public class bk { public static void main(String[] args) {
Test t = new Test();
new Thread(t).start();
}}

解决方案 »

  1.   

     wait();//这里加上时间就好了。比如wait(1000)
      

  2.   

    不好意思理解错了,debug了一下,运行到wait()的时候线程就停止了,下面这行notify()也就不会被执行
    线程不太懂,我再想想。顺便等高人来
      

  3.   

    你应该用另外一条线程notify它
    wait时都已经停止了哦,怎么会执行下面的代码呢?
      

  4.   

    恩恩,需要另外一个线程去监听这个线程的状态,然后notify,4楼正解
      

  5.   

    一个线程wait没有参数,自己进入等待队列.没有别人叫他.他都没机会运行呀.notify()执行不到呀.
    要写另外一个线程,调用notifyAll()/notify(),才能把他救出来呀.
      

  6.   

    当前的线程必须拥有此对象监视器。该线程发布对此监视器的所有权并等待,直到其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来。然后该线程将等到重新获得对监视器的所有权后才能继续执行。 对于某一个参数的版本,实现中断和虚假唤醒是可能的,而且此方法应始终在循环中使用:
      你的线程住于等待状态 
          你却又想让他去唤醒自己好像 没有 自己已经熟睡的 还可以随时叫醒自己    API 参考~。~
      

  7.   

    多谢上面的各位,我大概理解了你们的意思。我重新写了一下,不知道大家的意思是不是这样:将一个线程的对象作为参数传给另一个线程。是不是所有使用wait和notify的都得这么用啊?
    class Test implements Runnable { public void run() {
    try {
    while (true) {
    System.out.print(1);
    synchronized (this) {
    this.wait();
    }
    }
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }class Test1 implements Runnable { private Test test = null;

    Test1(Test t){test = t;}

    public void run() {
    while (true) {
    synchronized (test) {
    test.notify();
    }
    }
    }
    }public class bk { public static void main(String[] args) {
    Test t = new Test();
    new Thread(t).start();
    Test1 t1 = new Test1(t);
    new Thread(t1).start();
    }}
      

  8.   

    另外,我还发了一个帖子,也是notify的问题的,大家有空能去看一下的话,感激不尽。
    http://topic.csdn.net/u/20080326/17/7d00ce09-7d4c-4faf-9e15-d9fd324b60ac.html
      

  9.   

    自己睡着了wait开始等待,你自己可以叫醒你自己吗? 典型的....