您不能“通知主线程”。
最好的方法是使用ExecutorService
,例如:
import java.util.concurrent.*;
// in main thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(new Runnable() {
@Override
public void run() {
//Do something big...
}
});
future.get(); // blocks until the Runnable finishes
这些类是专门为处理异步操作而编写的,并且其中的所有代码都已经为您编写好了并且是防弹的。
编辑
如果您不想在等待时阻塞主线程,请在另一个线程中等待:
final Future<?> future = executorService.submit(new Runnable() {
@Override
public void run() {
//Do something big...
}
});
new Thread(new Runnable() {
@Override
public void run() {
future.get(); // blocks until the other Runnable finishes
// Do something after the other runnable completes
}
}).start();