弹簧螺纹中断

时间:2019-07-26 09:27:54

标签: java spring multithreading spring-boot

我有一个简单的弹簧控制器,它等待一些动作完成。假设它看起来像以下内容:

@GetMapping("/wait")
public void waitForFinish() throws InterruptedException {
    while (!allJobsAreFinished()) {
        Thread.sleep(5000);
    }
}

现在,由于某种原因,我想在一个单独的请求中中断此线程。为此,我将运行线程保存到映射中,并在其上的单独方法调用.interrupt()中:

private Map<String, Thread> runningThreads = new ConcurrentHashMap<>();

@GetMapping("/wait")
public void waitForFinish() throws InterruptedException {
    Thread currentThread = Thread.currentThread();
    runningThreads.put("testId", currentThread);
    //...
    runningThreads.remove("testId");
}

@GetMapping("/cancel")
public void cancel() {
    runningThreads.get("testId").interrupt();
}

我的问题如下:中断Spring创建的线程是一个好主意吗?如果我中断Spring线程怎么办?还是最好创建ExecutorService,向其提交我的任务,然后通过Future在其中中断任务?

1 个答案:

答案 0 :(得分:2)

请勿中断您不知道后果的线程。

对于您创建,启动的线程,您可能会知道这样做的副作用。