Java 停止';它已经在运行了

Java 停止';它已经在运行了,java,multithreading,spring-boot,executorservice,Java,Multithreading,Spring Boot,Executorservice,我有两个API:一个启动线程,另一个停止线程。我可以通过调用/startAPI成功地启动线程,但我无法通过调用/stopAPI停止已经在运行的线程。似乎执行器停止()什么也不做 MyRestController: @Autowired private Executor executor; @RequestMapping(path = "/start", method = GET) public ResponseEntity<HttpStatus> startLongTask() {

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

My
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);
}
以下是
方法执行

@Component
public class OtherService {

    public void methodImExecuting() {
        List<SomeObject> dataList = repository.getDataThatNeedsToBeFilled();
        for (SomeObject someObject : dataList) {
            gatewayService.sendDataToOtherResourceViaHttp(someObject);
        }
    }
}
@组件
公共服务{
公共无效方法执行(){
List dataList=repository.getDataThatNeedsToBeFilled();
对于(SomeObject SomeObject:dataList){
gatewayService.SendDataToutherResourceVIAHTTP(someObject);
}
}
}

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

Thread.currentThread().isInterrupted()
否则,发送中断信号无效

在这里你可以找到一个很好的解释:
简短回答:您不能停止不合作的正在运行的线程。线程有一个不推荐的
destroy()
方法,但这将导致VM处于“坏”状态

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

因此,您的
方法执行
应该如下所示:

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()的调用
将仅设置Executor服务中当前运行的所有线程的
interrupted
标志。要真正中断线程,线程必须自己检查
interrupted
标志是否已设置,然后抛出
InterruptedException

方法
methodImExecuting
如何对
executorService
尝试中断它作出反应,这一点很重要,所以我们需要看到这一点method@AndrewTobilko我在问题中添加了
methodImExecuting
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();
        }
        ...
    }