任何人都可以给我一个很好的小例子,演示java中的wait()和notify()函数。我已经尝试了下面的一段代码,但没有显示出我的预期。在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的方法是没有得到等待后执行,按我的想法SOP()应该执行。请帮我解决这个问题。
这不就是Google的用途吗? – mre
@Крысa:请记住,SO的目标之一是成为Google(和其他)搜索的热门。这是一个完全合理的问题。应该以一个例子来回答 - 在这里,在这里,不在其他地方 - 讨论(理想情况下)苏拉夫在上面出错的地方。 –
这个程序的预期行为是什么? – GETah