当我读到wait()和notify方法时,我正在读有关多线程的文章。我怀疑如果在wait()方法之前完成notify()方法会发生什么。
Wait()方法是否会再次等待?或者之前的通知是有效的,可以进一步移动?
发布于 2014-02-14 05:58:31
Object#wait()的javadoc说
会导致当前线程等待,直到另一个线程调用此对象的
java.lang.Object.notify()方法或java.lang.Object.notifyAll()方法。
所以,当你调用
someObject.wait();的调用之后,它将等待
someObject.notify(); // or notifyAll()发布于 2020-02-08 03:29:11
如果在wait()方法执行之前调用notify()方法,那么等待的线程将永远保持等待状态。在这种情况下,如果不能保证返回通知,则始终等待一段时间,例如,使用wait(milliSecond)/wait(milliSecond,NanoSecond)而不是wait(),它将等待无限的时间,只有在收到通知时才会继续。
请参考下面的示例,以便更好地理解-
class MainThread extends Thread {
public void run() {
ChildThread ct = new ChildThread();
ct.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
synchronized (ct) {
System.out.println("Main Thread started");
try {
ct.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main THread controlled returned");
System.out.println(ct.total);
}
}}
class ChildThread extends Thread {
int total = 0;
public void run() {
synchronized (this) {
System.out.println("Child Thread started");
for (int i = 0; i < 100; i++) {
total++;
}
System.out.println("Child Thread passed notify");
this.notify();
}
}}
public class HelloWorld {
public static void main(String args[]) throws InterruptedException, IOException {
MainThread mt = new MainThread();
mt.start();
}}https://stackoverflow.com/questions/21766362
复制相似问题