如何在Java中终止主线程时停止另一个线程?



我有一个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);

我想立即关闭或取消另一个没有主线程的线程。

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*** 
}
}
}

我看到了这个,如何在另一个线程仍在运行时停止主线程,但我认为这与我的情况相反。

你必须让线程成为守护进程。为此,必须在创建scheduleservice时提供ThreadFactory:

ThreadFactory threadFactory = (task) -> {
Thread thread = new Thread(task);
thread.setDaemon(true);
return thread;
};
ScheduledExecutorService schedulService = Executors.newScheduledThreadPool(1, threadFactory);

最新更新