• Java Concurrency


    When you work with an executor, you don't have to manage threads. You only implement the Runnable or Callable tasks and send them to the executor. It's the executor that's responsible for creating threads, managing them in a thread pool, and finishing them if they are not needed. Sometimes, you may want to cancel a task that you sent to the executor. In that case, you can use the cancel() method of Future that allows you to make that cancellation operation. In this recipe, you will learn how to use this method to cancel the tasks that you have sent to an executor.

    /**
     * This class implements the task of the example. It simply writes a message
     * to the console every 100 milliseconds 
     */
    public class Task implements Callable<String> {
    
        /**
         * Main method of the task. It has an infinite loop that writes a message to
         * the console every 100 milliseconds
         */
        @Override
        public String call() throws Exception {
            while (true){
                System.out.printf("Task: Test
    ");
                Thread.sleep(100);
            }
        }
    }
    
    
    
    /**
     * Main class of the example. Execute a task trough an executor, waits
     * 2 seconds and then cancel the task.
     */
    public class Main {
    
        public static void main(String[] args) {
    
            // Create an executor
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    
            // Create a task
            Task task = new Task();
    
            System.out.printf("Main: Executing the Task
    ");
    
            // Send the task to the executor
            Future<String> result = executor.submit(task);
    
            // Sleep during two seconds
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            // Cancel the task, finishing its execution
            System.out.printf("Main: Cancelling the Task
    ");
            result.cancel(true);
            // Verify that the task has been cancelled
            System.out.printf("Main: Cancelled: %s
    ", result.isCancelled());
            System.out.printf("Main: Done: %s
    ", result.isDone());
    
            // Shutdown the executor
            executor.shutdown();
            System.out.printf("Main: The executor has finished
    ");
        }
    }

    You use the cancel() method of the Future interface when you want to cancel a task that you have sent to an executor. Depending on the parameter of the cancel() method and the status of the task, the behavior of this method is different:

    • If the task has finished or has been canceled earlier or it can't be canceled for other reasons, the method will return the false value and the task won't be canceled.
    • If the task is waiting in the executor to get a Thread object that will execute it, the task is canceled and never begins its execution. If the task is already running, it depends on the parameter of the method. The cancel() method receives a Boolean value as a parameter. If the value of that parameter is true and the task is running, it will be canceled. If the value of the parameter is false and the task is running, it won't be canceled.

    The following snippet shows the output of an execution of this example:

    Main: Executing the Task
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Task: Test
    Main: Cancelling the Task
    Main: Cancelled: true
    Main: Done: true
    Main: The executor has finished
  • 相关阅读:
    Python在计算内存时应该注意的问题?
    如何高效地远程部署?自动化运维利器 Fabric 教程
    强大的 Python 任务自动化工具!invoke 十分钟入门指南
    进一步学习 nox 教程,轻松掌握命令行用法
    Oracle Solaris 11.4安装桌面/gdb
    Solaris 10上Oracle 10g安装步骤图解
    Oracle Solaris 10图文安装
    读取模式下cbc latch的事件模拟(热块竞争和热链竞争)-P62
    关于位图数据位和系统管理区大小-P6
    关于位图数据和标记位-P3
  • 原文地址:https://www.cnblogs.com/huey/p/6040286.html
Copyright © 2020-2023  润新知