在我的应用程序,我已经在后台线程运行下面的代码:爪哇 - 等待了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完成执行后继续。有人告诉我,上面的代码应该注意的是,但有两件事情我不明白:
如果后台线程获得myRunnable的锁,那么不应该myRunnable块它能够前调用notify()?
如何知道notify()在wait()之前未被调用?
你可能要考虑通过[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)等待'/'通知' –
为什么不使用'''Thread.join()'''? – saka1029