2015-12-25 57 views
1

在我的应用程序,我已经在后台线程运行下面的代码:爪哇 - 等待了Runnable完成

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

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

//rest of my code 

而且MyRunnable看起来是这样的:

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

     //do some tasks 

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

我想在后台线程在myRunnable完成执行后继续。有人告诉我,上面的代码应该注意的是,但有两件事情我不明白:

  1. 如果后台线程获得myRunnable的锁,那么不应该myRunnable块它能够前调用notify()?

  2. 如何知道notify()在wait()之前未被调用?

+0

你可能要考虑通过[ListenableFuture#的addListener]实施这个(http://docs.guava-libraries.googlecode.com/git/ javadoc/com/google/common/util/concurrent/ListenableFuture.html#addListener(java.lang.Runnable,%20java.util.concurrent.Executor))(for Java7)or [CompletableFuture#thenRunAsync](https:// docs .oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenRunAsync-java.lang.Runnable-java.util.concurrent.Executor-)(for Java8)等待'/'通知' –

+0

为什么不使用'''Thread.join()'''? – saka1029

回答

3
  1. myRunnable.wait()将发布的myRunnable锁,并等待通知
  2. 我们总是在等待之前添加支票。

    //synchronized wait block 
    while(myRunnable.needWait){ 
        myRunnable.wait(); 
    } 
    
    //synchronized notify block 
    this.needWait = false; 
    myRunnable.notify(); 
    
0
  1. 当等待开始
  2. 这是一个可能的锁被释放,你可以通过将runOnUiThread的​​块内太(这样可运行无法获取锁,直到避免其他线程已经等待)
0

创建一个名为Objectlock。然后在runOnUiThread(myRunnable);之后,您可以拨打lock.wait()。当你的myRunnable完成它的工作,请拨打lock.notify()。但是您必须声明MyRunnable为内部类,因此它们可以共享lock对象。

2

您也可以使用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 
}