简体   繁体   English

Java - 等待Runnable完成

[英]Java - Wait for Runnable to finish

In my app, I have the following code running on a background thread: 在我的应用程序中,我在后台线程上运行以下代码:

MyRunnable myRunnable = new MyRunnable();
runOnUiThread(myRunnable);

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

//rest of my code

And MyRunnable looks like this: MyRunnable看起来像这样:

public class MyRunnable implements Runnable {
    public void run() {

        //do some tasks

        synchronized (this) {
            this.notify();
        }
    }
}

I want the background thread to continue after myRunnable has finished executing. 我想在myRunnable完成执行后继续后台线程。 I've been told that the above code should take care of that, but there are two things I don't understand: 我被告知上面的代码应该注意这一点,但有两件事我不明白:

  1. If the background thread acquires myRunnable's lock, then shouldn't myRunnable block before it's able to call notify() ? 如果后台线程获取myRunnable的锁,那么在它能调用notify()之前不应该myRunnable阻塞吗?

  2. How do I know that notify() isn't called before wait() ? 我怎么知道在wait()之前没有调用notify()?

  1. myRunnable.wait() will release the lock of myRunnable and wait notify myRunnable.wait()将释放myRunnable的锁并等待notify
  2. we always add a check before wait. 我们总是在等待前添加支票。

     //synchronized wait block while(myRunnable.needWait){ myRunnable.wait(); } //synchronized notify block this.needWait = false; myRunnable.notify(); 

You could also use JDK's standard RunnableFuture like this: 你也可以像这样使用JDK的标准RunnableFuture

RunnableFuture<Void> task = new FutureTask<>(runnable, null);
runOnUiThread(task);
try {
    task.get(); // this will block until Runnable completes
} catch (InterruptedException | ExecutionException e) {
    // handle exception
}
  1. The lock is released when the wait starts 等待开始时锁定被释放
  2. That's a possibility, you can avoid it by putting the runOnUiThread within the synchronized block too (so that the runnable can't acquire the lock until the other thread is already waiting) 这是一种可能性,您可以通过将runOnUiThread放在synchronized块中来避免它(以便runnable无法获取锁,直到另一个线程已经在等待)

Create an Object called lock . 创建一个名为lockObject Then after runOnUiThread(myRunnable); 然后在runOnUiThread(myRunnable); , you can call lock.wait() . ,你可以调用lock.wait() And when your myRunnable is finish it's job, call lock.notify() . 当你的myRunnable完成它的工作时,调用lock.notify() But you must declare MyRunnable as inner class, so they can share the lock object. 但是您必须将MyRunnable声明为内部类,以便它们可以共享lock对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM