【问题标题】:How to stop another thread when main thread is terminated in Java?java - 当主线程在Java中终止时如何停止另一个线程?
【发布时间】: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


【解决方案1】:

您必须创建线程守护程序。为此,您必须在创建 schedulService 时提供 ThreadFactory

    ThreadFactory threadFactory = (task) -> {
        Thread thread = new Thread(task);
        thread.setDaemon(true);
        return thread;
    };

    ScheduledExecutorService schedulService = Executors.newScheduledThreadPool(1, threadFactory);

【讨论】:

  • 感谢您的回答。我试过了。当我使用 newSingleThreadExecutor 时它运行良好但是当我尝试然后我使用 scheduleWithFixedDelay 时,线程没有终止但是所有工作线程都完成了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多