调度程序通过新的单线程从服务器获取配置。但即使调度程序正在执行 config() 以从服务器获取配置,应用程序也会继续执行。
App{
XXXX;
XXXX;
try{
scheduler()
} catch(Exception e){
}
public void scheduler(){
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
Callable<Void> callable = new Callable<Void>() {
public Void call() throws Exception {
try {
config();
} finally {
service.schedule(this, TimeOut(), TimeUnit.SECONDS);
}
return null;
}
};
service.schedule(callable, 0, TimeUnit.SECONDS);
}
如何让主线程等待,直到单线程获取配置完成。
最佳答案
在触发 ExecutorService#shutdown()
后尝试使用 ExecutorService#awaitTermination(time, unit)
:
ExecutorService#awaitTermination() blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
service.shutdown();
try {
// Use Long.MAX_VALUE to wait forever, see link below
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
// TODO ...
}
关于java - 让主线程等待,直到新的单线程在java中完全执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48161365/