所以我一直在研究一個簡單的等待/通知的例子在Java中,由於某些原因,我一直無法讓它正常運行。如果有人能夠看到可能是什麼問題,將非常感謝!Java等待/通知不起作用
public class ThreadDemonstration
{
private String str = null;
Thread stringCreator = new Thread(new Runnable()
{
public void run()
{
synchronized(this)
{
str = "I have text";
notify();
}
}
});
private Thread stringUser = new Thread(new Runnable()
{
public void run()
{
synchronized(this)
{
if(str == null)
{
try {
System.out.println("str is null, I need help from stringCreator");
wait();
System.out.println(str);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
});
public static void main (String [] args)
{
ThreadDemonstration td = new ThreadDemonstration();
td.stringUser.start();
td.stringCreator.start();
}
}
我的電流輸出爲: str是空的,我需要從stringCreator
幫助,所以出於某種原因線程stringCreator沒有醒stringUser還是我失去了完全是另一回事?
謝謝!
您認爲'new'的Runnable(){...}'值是多少? – Pshemo
我現在明白了,謝謝:) –