Ensure that a task is interruptible

前端 未结 2 1247
生来不讨喜
生来不讨喜 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:27

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

    Calling future.cancel(...) will stop the task it has not been run yet. If it is being run then if you use future.cancel(true) it will interrupt the running thread.

    To stop the thread you need to test the thread interrupt flag:

    if (!Thread.currentThread().isInterrupted()) {
       ...
    

    And you need to handle handle InterruptedException appropriately. For example:

    try {
        Thread.sleep(...);
    } catch (InterruptedException e) {
        // re-establish the interrupt condition
        Thread.currentThread.interrupt();
        // probably stop the thread
        return;
    }
    

    See my answer about threads not interrupting.

提交回复
热议问题