任何人都可以給我一個很好的小例子,演示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