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\n");
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\n"); // 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\n");
result.cancel(true);
// Verify that the task has been cancelled
System.out.printf("Main: Cancelled: %s\n", result.isCancelled());
System.out.printf("Main: Done: %s\n", result.isDone()); // Shutdown the executor
executor.shutdown();
System.out.printf("Main: The executor has finished\n");
}
}

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

Java Concurrency - 取消线程执行器中的线程的更多相关文章

  1. Java 线程池中的线程复用是如何实现的?

    前几天,技术群里有个群友问了一个关于线程池的问题,内容如图所示: 关于线程池相关知识可以先看下这篇:为什么阿里巴巴Java开发手册中强制要求线程池不允许使用Executors创建? 那么就来和大家探讨 ...

  2. 【高并发】通过源码深度分析线程池中Worker线程的执行流程

    大家好,我是冰河~~ 在<高并发之--通过ThreadPoolExecutor类的源码深度解析线程池执行任务的核心流程>一文中我们深度分析了线程池执行任务的核心流程,在ThreadPool ...

  3. java使用Executor(执行器)管理线程

    一.一个实现了Runnable接口的类 class MyThread implements Runnable{ private static int num = 0; @Override public ...

  4. Java自学-图形界面 Swing中的线程

    Swing中的线程 步骤 1 : 三种线程 在Swing程序的开发中,需要建立3种线程的概念 初始化线程 初始化线程用于创建各种容器,组件并显示他们,一旦创建并显示,初始化线程的任务就结束了. 事件调 ...

  5. 《Java Concurrency》读书笔记,构建线程安全应用程序

    1. 什么是线程安全性 调用一个函数(假设该函数是正确的)操作某对象常常会使该对象暂时陷入不可用的状态(通常称为不稳定状态),等到操作完全结束,该对象才会重新回到完全可用的状态.如果其他线程企图访问一 ...

  6. 【java并发】传统线程技术中创建线程的两种方式

    传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...

  7. 深入浅出 Java Concurrency (27): 并发容器 part 12 线程安全的List/Set[转]

    本小节是<并发容器>的最后一部分,这一个小节描述的是针对List/Set接口的一个线程版本. 在<并发队列与Queue简介>中介绍了并发容器的一个概括,主要描述的是Queue的 ...

  8. Java并发基础01. 传统线程技术中创建线程的两种方式

    传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...

  9. Java Concurrency - ThreadFactory, 使用工厂方法创建线程

    当需要创建多个类似的线程实例时,使用工厂模式替代 new 操作符创建线程,能使代码更为简洁,易于维护.JDK 提供了 java.util.concurrent.ThreadFactory 接口,Thr ...

随机推荐

  1. JavaScript继承方式详解

    原文链接 : http://segmentfault.com/a/1190000002440502 js继承的概念 js里常用的如下两种继承方式: 原型链继承(对象间的继承) 类式继承(构造函数间的继 ...

  2. HDU 3790 最短路径问题 (最短路)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3790 简单的最短路问题,这题听说有重边.我用spfa和dijkstra写了一遍,没判重边,速度都差不多 ...

  3. Http Header Content-Disposition

    Content-Disposition用途 Content-Disposition是为了实现服务器下载文件功能,并可提供文件名. Content-Disposition格式 content-dispo ...

  4. HR(人事管理)

    HRMS(Human Resource Management System) --人员 per_people_f --人员分配 per_all_assignments_f --要素 DECLARE l ...

  5. python的random模块

    As an example of subclassing, the random module provides the WichmannHill class that implements an a ...

  6. Oracle DataGuard搭建(一)

    第一次搭建oracle dataguard.学oracle很长时间,却没有完整的搭过dg,说起来让人笑.总得有第一次,而且第一次总是很痛苦的. 数据库版本: Oracle Database 11g E ...

  7. java foreach编辑讲解

    foreach语句使用总结 foreach语句是java5的新特征之一,在遍历数组.集合方面,foreach为开发人员提供了极大的方便. foreach语句是for语句的特殊简化版本,但是foreac ...

  8. Amazon DynamoDB 概览

    1. 什么是Amazon DynamoDB DynamoDB 是一种快速.全面受管的 NoSQL 数据库服务,它能让用户以简单并且经济有效地方式存储和检索任何数据量,同时服务于任何程度的请求流量.所有 ...

  9. [WebGL] Setting Up WebGL

    In this lesson we cover setting up WebGL for use, including creating a canvas, getting the WebGL ren ...

  10. Swift常用语法示例代码(一)

    此篇文章整理自我以前学习Swift时的一些练习代码,其存在的意义多是可以通过看示例代码更快地回忆Swift的主要语法. 如果你想系统学习Swift或者是Swift的初学者请绕路,感谢Github上Th ...