Futrue cancel() mayInterruptIfRunning 的含义

源码注释

 * @param mayInterruptIfRunning {@code true} if the thread executing this
 * task should be interrupted; otherwise, in-progress tasks are allowed
 * to complete

翻译成如下:

mayInterruptIfRunning为true,该task正在执行,这个task应该被中断;
mayInterruptIfRunning为false,该task正在执行,这个task将会继续执行到完成。

加深理解

做四个测试

  • mayInterruptIfRunning为true,cancel 正在执行的task
  • mayInterruptIfRunning为false,cancel 正在执行的task
  • mayInterruptIfRunning为true,cancel 还没有执行的task
  • mayInterruptIfRunning为false,cancel 还没有执行的task

测试代码

   @Test
    public void test() throws ExecutionException, InterruptedException {
        ExecutorService pool =Executors.newFixedThreadPool(1);
        Future future1 = pool.submit(new MyCallable("task1"));
        Future future2 = pool.submit(new MyCallable("task2"));
         /**
         *   测试1
         *   future1.cancel(true);
         *         future2.get();
         */

        /**
         *   测试2
         *   future1.cancel(false);
         *         future2.get();
         */

        /**
         *   测试3
         *   future2.cancel(true);
         *         future1.get();
         */

        /**
         *   测试4
         *   future2.cancel(false);
         *         future1.get();
         */
    }
    
     private class MyCallable implements Callable {
        private String name;
        public MyCallable(String name){
            this.name = name;
        }
        @Override
        public Integer call() throws Exception {
            System.out.println(name+"开始执行");
            Thread.sleep(1000);
            System.out.println(name+"执行完成");
            return 3;
        }
    }

测试1: task1正在执行,task2还没执行,cancel task1,mayInterruptIfRunning为true
输出结果如下:
在这里插入图片描述
说明:task1被中断了

测试2: task1正在执行,task2还没执行,cancel task1,mayInterruptIfRunning为false
输出如下:
Futrue cancel() mayInterruptIfRunning 的含义_第1张图片
说明:task1没有被中断

测试3: task1正在执行,task2还没执行,cancel task2,mayInterruptIfRunning为true
输出如下:
在这里插入图片描述
说明:task2被中断了

测试4: task1正在执行,task2还没执行,cancel task2,mayInterruptIfRunning为false
输出如下:
在这里插入图片描述
说明:task2被中断了

结论

  • mayInterruptIfRunning为true,cancel的任务正在执行,那么就会被中断。cancel的任务被安排将来执行也会被中断(其实就是不执行)
  • mayInterruptIfRunning为false,cancel的任务正在执行,那么就不会被中断。cancel的任务被安排将来执行会被中断(其实就是不执行)

你可能感兴趣的:(java基础)