停止已经在运行的线程

时间:2018-09-13 13:24:07

标签: java multithreading spring-boot executorservice

我有两个API:一个启动线程,另一个停止线程。我可以通过调用/start API成功启动线程,但是我无法通过调用/stop API停止已经运行的线程。似乎Executor#stop()什么也没做。

我的RestController

@Autowired
private Executor executor;

@RequestMapping(path = "/start", method = GET)
public ResponseEntity<HttpStatus> startLongTask() {
    executor.start();
    return ResponseEntity.ok(HttpStatus.OK);
}

@RequestMapping(path = "/stop", method = GET)
public ResponseEntity<HttpStatus> stopLongTask() {
    executor.stop();
    return ResponseEntity.ok(HttpStatus.OK);
}

我的Executor

@Component
public class Executor {

    @Value("${threads.number}")
    private int threadsNumber;

    private ExecutorService executorService;

    @Autowired
    private OtherService otherService;

    @PostConstruct
    private void init() {
        executorService = Executors.newFixedThreadPool(threadsNumber);
        executorService = Executors.newScheduledThreadPool(threadsNumber);
    }

    /**
     * Start.
     */
    public void start() {
        executorService.submit(() -> otherService.methodImExecuting());
    }

    /**
     * Stop.
     */
    @PreDestroy
    publicvoid stop() {
        executorService.shutdownNow();
        try {
            if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }
}

这里是methodImExecuting

@Component
public class OtherService {

    public void methodImExecuting() {
        List<SomeObject> dataList = repository.getDataThatNeedsToBeFilled();
        for (SomeObject someObject : dataList) {
            gatewayService.sendDataToOtherResourceViaHttp(someObject);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

简短的回答:您无法停止不合作的正在运行的线程。有一种不推荐使用的destroy()方法用于线程,但这将导致您的VM处于“不良”状态。

结束线程清除的唯一可能性是中断它。但是检查中断是线程本身的任务。

因此,您的methodImExcecuting充满生气:

void methodImExecuting() throws InterruptedException {
    // it depends on your implementation, I assume here that you iterate 
    // over a collection for example
    int loopCount = 0;
    for (Foo foo : foos) {
        ++loopCount;
        if (loopCount % 100 == 0) {
            if (Thread.interrupted())
                throw new InterruptedException();
        }
        ...
    }

这取决于您的实现,如果线程被中断,您必须多久查看一次。但是事实是,对executorService.shutdownNow();的调用只会设置executorService中当前正在运行的所有线程的interrupted标志。要真正中断线程,线程必须自己检查是否设置了interrupted标志,然后抛出InterruptedException

答案 1 :(得分:1)

您正在运行的线程必须对中断信号做出反应

tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='scatter', joint_kws=dict(marker='D', s=50))

否则,发送中断信号无效。

在这里您可以找到很好的解释: Difference between shutdown and shutdownNow of Executor Service