【发布时间】:2021-11-22 18:54:39
【问题描述】:
我有一个 REST 控制器。它创建了两个线程,一个是调度器,它正在搜索数据库的数据以判断用户是否退出,另一个是执行器,并向客户端返回200成功代码。
如果主线程正在检查另外两个线程,它工作得很好。
public boolean foo() {
//flag whether is exited by User
Boolean exited = false;
//create a scheduler
ScheduledExecutorService schedulService = Executors.newScheduledThreadPool(1);
//It is worked each 20 second
schedulService.scheduleWithFixedDelay(new FooSchdlue(exited), 0, 2000,TimeUnit.MILLISECONDS);
//create a executor
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> futrue = executor.submit(new FooExecutor());
// I want this Because this is not stopped
// Therefore I cant't return true until process is done
while (!exited && !futrue.isDone()) {
}
//All thread is exited
schedulService.shutdownNow();
futrue.cancel(true);
return true;
}
但是,在另外两个线程完成之前,它不能返回 true。
// I want this Because this is not stopped
// Therefore I cant't return true until process is done
//while (!exited && !futrue.isDone()) {
//}
//All thread is exited
//schedulService.shutdownNow();
//futrue.cancel(true);
我想shutdownNow或取消另一个没有主线程的线程。
class FooSchdlue implements Runnable{
Boolean exited = false;
public FooSchdlue(Boolean exited) {
this.exited = exited;
}
@Override
public void run() {
// Database check
if(foo.getExitFlag() == true) {
exited = true;
***exit Another sub thread***
}
}
}
我看到了这个,how to stop main thread while another thread still running,但我认为这与我的情况相反。
【问题讨论】:
-
通常,您不应该手动终止线程,而是将所有辅助线程标记为守护进程。当没有非守护进程运行线程离开时,这将自动终止它们。可以在线程启动之前为其设置守护程序标志。
标签: java multithreading