所以我一直在用 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 或者我完全错过了其他东西?
谢谢!