小编Rob*_*n A的帖子

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 …
Run Code Online (Sandbox Code Playgroud)

java notify wait

1
推荐指数
1
解决办法
7983
查看次数

标签 统计

java ×1

notify ×1

wait ×1