如何等待并通知工作?

我需要知道wait()和notify()是如何工作的? 我无法通过使用wait()和notify()来实现它的工作。 相反,如果我使用while()循环进行等待,它可以正常工作。 怎么回事? 为什么我不能简单地使用wait()和notify()?

你读过wait – notify函数的文档吗?

无论如何,为了实现等待通知机制的最佳方式,使用类似的东西(基于这个网站 ):

public class WaitNotifier { private final Object monitoredObject = new Object(); private boolean wasSignalled = false; /** * waits till another thread has called doNotify (or if this thread was interrupted), or don't if was already * notified before */ public void doWait() { synchronized (monitoredObject) { while (!wasSignalled) { try { monitoredObject.wait(); } catch (final InterruptedException e) { break; } } wasSignalled = false; } } /** * notifies the waiting thread . will notify it even if it's not waiting yet */ public void doNotify() { synchronized (monitoredObject) { wasSignalled = true; monitoredObject.notify(); } } } 

请注意,此类的每个实例只应使用一次,因此如果需要多次使用它,可能需要更改它。

wait()和notify()在synchronized块中使用,同时使用线程挂起并从中断处继续。

等待立即失去锁定,而Nofity仅在遇到结束括号时才会离开锁定。

您还可以参考此示例示例:

 public class MyThread implements Runnable { public synchronized void waitTest() { System.out.println("Before Wait"); wait(); System.out.println("After Wait"); } public synchronized void notifyTest() { System.out.println("Before Notify"); notify(); System.out.println("After Notify"); } } public class Test { public static void main(String[] args) { Thread t = new Thread(new MyThread()); t.start(); } }