所以我一直在研究一个简单的等待/通知的例子在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
我现在明白了,谢谢:) –