【发布时间】:2011-12-02 15:27:25
【问题描述】:
谁能给我一个很好的小例子来演示java中的wait()和notify()功能。我已经尝试使用下面的代码,但它没有显示我的预期。
public class WaitDemo {
int i = 10;
int display() {
System.out.println("Lexmark");
i++;
return i;
}
}
public class ClassDemo1 extends Thread {
private WaitDemo wd = new WaitDemo();
public static void main(String[] args) {
ClassDemo1 cd1 = new ClassDemo1();
ClassDemo1 cd2 = new ClassDemo1();
cd1.setName("Europe");
cd2.setName("America");
cd1.start();
cd2.start();
}
synchronized void display() {
System.out.println("Hello");
notifyAll();
}
public void run() {
synchronized (this) {
try {
{
notify();
System.out.println("The thread is " + currentThread().getName());
wait();
System.out.println("The value is " + wd.display());
}
} catch (InterruptedException e) {
}
}
}
}
问题是 WaitDemo 类中的方法没有被执行,按照我的想法,wait() 之后的 SOP 应该执行。请帮我解决这个问题。
【问题讨论】:
-
这不就是谷歌的目的吗?
-
@Крысa:请记住,SO 的目标之一是成为 Google(和其他)搜索的热门搜索。这是一个完全合理的问题。应该用一个例子来回答——这里是关于 SO,而不是其他地方——并讨论(理想情况下)Sourav 在上面哪里出错了。
-
这个程序的预期行为是什么?
-
Sourav,为了帮助人们帮助你,请获得一个好的代码格式化程序来处理... 不寻常 ...代码缩进样式。我不是要发起一场风格大战,但你必须接受上述不是通常的事情,保持通常的事情会帮助人们帮助你。恕我直言,它看起来真的很草率且难以理解,根本不像真正的风格...... 更新:啊,@Alex K 为你修好了。
标签: java multithreading wait notify