在我的應用程序,我已經在後臺線程運行下面的代碼:爪哇 - 等待了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