Ensure that a task is interruptible

前端 未结 2 1231
生来不讨喜
生来不讨喜 2021-01-20 15:12

How to ensure that my tasks are responsive to interruption when I call Future.cancel()?

ExecutorService         


        
2条回答
  •  北海茫月
    2021-01-20 15:28

    In your task Runnable, make sure at different levels where you do a interrupt check. Something like:

    while(!Thread.currentThread().isInterrupted()){
        //do something
    }
    

    If your logic in not something like loop, then check for interrupt status right before major computation like database or web-service call.

    The idea here is to keep checking interrupt status as when future.cancel(true) is called, it ultimately interrupts your thread running task. This is kind of a way to know when to terminate.

提交回复
热议问题