在等待另一个线程时让当前线程休眠

One*_*ree 0 java multithreading notify wait

在我的应用程序的某个时刻,我想让我的主线程(即当前正在执行的线程)休眠一段时间或直到后台完成(并唤醒它),以先到者为准。

这是我所做的(我认为会起作用,但没有)

public static void main(String args[])
{
    // .... other stuff ...

    // show a splash screen
    // just think of this as an image
    showPlashScreen(): 
    new Thread(new Runnable()
    {
          public void run()
          {
                // do some work here

                // notify everyone after the work is done
                Thread.currentThread().notifyAll();
          }
    }).start();

    // now make the current thread to wait for the background
    // or for at most 1000
    Thread.currentThread().wait(1000);
    disposeSplashScreen();

    // ... other stuff ....
}
Run Code Online (Sandbox Code Playgroud)

执行这个,我不断得到 java.lang.IllegalMonitorStateException

(部分)堆栈跟踪:

Caused by: java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)

.... <cut> ....

Exception in thread "Thread-7" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
Run Code Online (Sandbox Code Playgroud)

Sen*_*rJD 5

为了能够调用notify(),您需要在同一个对象上进行同步。

synchronized (someObject) {
    someObject.wait();
}

/* different thread / object */
synchronized (someObject) {
    someObject.notify();
}
Run Code Online (Sandbox Code Playgroud)