如何在 Java 中使用 wait()/notify()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11526374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use wait()/notify() in Java
提问by jrad
I know that there are a few threads open regarding this topic, but I'm just looking for a VERY ELEMENTARY example of how to use wait() and notify() in Java. By "VERY ELEMENTARY," I mean simply printing something out. Thanks.
我知道关于这个主题有几个线程开放,但我只是在寻找一个关于如何在 Java 中使用 wait() 和 notify() 的非常基本的例子。“非常基本”,我的意思是简单地打印出一些东西。谢谢。
EDIT: Here's what I have tried thus far and I get an IllegalMonitorStateException:
编辑:这是我迄今为止尝试过的,我得到了一个 IllegalMonitorStateException:
public void waiting() {
for(int i = 0; i < 10; i++) {
if(i == 5)
try {
this.wait();
} catch (InterruptedException e) {
}
else
System.out.println(i);
}
System.out.println("notify me now");
this.notify();
}
public void waiting() {
for(int i = 0; i < 10; i++) {
if(i == 5)
try {
this.wait();
} catch (InterruptedException e) {
}
else
System.out.println(i);
}
System.out.println("notify me now");
this.notify();
}
采纳答案by Kumar Vivek Mitra
wait and notify are used in synchronized blockwhile using threads to suspend and resume where left off.
等待和通知在同步块中使用,同时使用线程在停止的地方挂起和恢复。
Wait immediately looses the lock, whereas Nofity will leave the lock only when the ending bracket is encountered.
Wait 会立即解除锁定,而 Nofity 仅在遇到结束括号时才会解除锁定。
public class Mythread implements Runnable{
public synchronized void goo(){
System.out.println("Before Wait");
wait();
System.out.println("After Wait");
}
public synchronized void foo(){
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();
}
}
回答by Eric Lindauer
Your IllegalMonitorStateException is due to the fact that you must synchronize on the object before calling wait or notify. So
您的 IllegalMonitorStateException 是由于您必须在调用 wait 或 notify 之前对对象进行同步。所以
this.wait
this.wait
needs to be
需要是
synchronized(this) {
this.wait();
}
Your example won't run because you'll never get to the notify
call... as soon as your thread hits wait, it will suspend and advance no further. For wait / notify to work, you have to have two threads. One thread suspends when the wait
method is invoked, and eventually, the second thread calls synchronized(this) { this.notify() }
to cause the first thread to wake up and continue executing below the wait call.
您的示例将不会运行,因为您永远不会接到notify
电话……只要您的线程等待,它就会暂停并不再前进。为了等待/通知工作,你必须有两个线程。wait
调用该方法时,一个线程挂起,最终,第二个线程调用synchronized(this) { this.notify() }
使第一个线程唤醒并在等待调用下方继续执行。
The synchronization is required because you would ordinarily check some condition before waiting, ie,
同步是必需的,因为您通常会在等待之前检查某些条件,即,
synchronized(this) {
if(! this.isReady) {
this.wait();
}
}
You need to synchronize to make sure no other thread changes the state of the isReady flag between the line where you check the variable and the line where you wait. So your notify code would
您需要同步以确保没有其他线程在检查变量的行和等待的行之间更改 isReady 标志的状态。所以你的通知代码会
synchronized(this) {
isReady = true;
this.notify();
}
Now the order of the method calls doesn't matter. If you notify first, no thread will wake up, but that's ok, because you aren't going to sleep since isReady = true. If you go to sleep first, isReady = true does nothing, but the notify call wakes up the thread. Finally, the synchronization ensures that you don't check the variable in thread A, then have thread B set the variable and notify (doing nothing), then have thread A go to sleep and never wake up.
现在方法调用的顺序无关紧要。如果您先通知,则不会有线程被唤醒,但这没关系,因为您不会因为 isReady = true 而睡觉。如果您先进入睡眠状态,则 isReady = true 什么也不做,但通知调用会唤醒线程。最后,同步确保您不会检查线程 A 中的变量,然后让线程 B 设置变量并通知(什么都不做),然后让线程 A 进入睡眠状态并且永不醒来。
Hope that helps.
希望有帮助。
回答by Nathan White
wait()
and notify()
are used to synchronise threads: a thread can be told to wait()
, and will not continue doing anything until it receives the notify()
call.
wait()
和notify()
用于同步线程:线程可以被告知wait()
,并且在收到notify()
调用之前不会继续做任何事情。
回答by Jonatan
The basic idea with these functions is that wait()
suspends a thread (puts it to sleep), and notify()
causes a thread to pick up where it left when it went to sleep.
这些函数的基本思想是wait()
挂起一个线程(使其进入睡眠状态),notify()
并使线程在它进入睡眠状态时从它离开的地方开始。
回答by nook
回答by munyengm
See this exampleon guarded blocks from the oracle java site - it includes a worked example of a simple producer-consumer problem.
请参阅oracle java 站点上有关受保护块的此示例- 它包含一个简单的生产者-消费者问题的有效示例。