Java 等待前通知

Java 等待前通知,java,multithreading,Java,Multithreading,当我读到wait()和notify方法时,我正在读多线程。我怀疑如果notify()方法在wait()方法之前完成,会发生什么情况 Wait()方法是否将再次等待?或者之前的通知对进一步移动有效?的javadoc表示 使当前线程等待,直到另一个线程调用 java.lang.Object.notify()方法或java.lang.Object.notifyAll() 此对象的方法 那么,当你打电话的时候 someObject.wait(); 它将等待调用 someObject.notify();

当我读到
wait()
notify
方法时,我正在读多线程。我怀疑如果
notify()
方法在
wait()
方法之前完成,会发生什么情况

Wait()
方法是否将再次等待?或者之前的通知对进一步移动有效?

的javadoc表示

使当前线程等待,直到另一个线程调用
java.lang.Object.notify()
方法或
java.lang.Object.notifyAll()
此对象的方法

那么,当你打电话的时候

someObject.wait();
它将等待调用

someObject.notify(); // or notifyAll()
如果在执行wait()方法之前调用notify()方法,那么等待的线程将永远处于等待状态。 在这种情况下,如果无法保证返回通知,则始终等待一段时间,即使用wait(毫秒)/wait(毫秒,纳秒),而不是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();
}}
class主线程扩展线程{
公开募捐{
ChildThread ct=新的ChildThread();
ct.start();
试一试{
睡眠(5000);
}捕捉(中断异常e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
同步(ct){
System.out.println(“主线程已启动”);
试一试{
ct.wait();
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
System.out.println(“主线程控制返回”);
系统输出打印项次(ct总数);
}
}}
类ChildThread扩展线程{
int-total=0;
公开募捐{
已同步(此){
System.out.println(“子线程已启动”);
对于(int i=0;i<100;i++){
总计++;
}
System.out.println(“传递的子线程通知”);
this.notify();
}
}}
公共类HelloWorld{
公共静态void main(字符串args[])引发InterruptedException,IOException{
主线程mt=新的主线程();
mt.start();
}}

我希望您知道您可以试试。我试过了,以前的通知很好…但仍然可以确认。。我是对的?你是说以前的通知是valid@user2985842我是说在等待()之前发生的
notify()
对它绝对没有影响。