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\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 - 取消线程执行器中的线程的更多相关文章
- Java 线程池中的线程复用是如何实现的?
前几天,技术群里有个群友问了一个关于线程池的问题,内容如图所示: 关于线程池相关知识可以先看下这篇:为什么阿里巴巴Java开发手册中强制要求线程池不允许使用Executors创建? 那么就来和大家探讨 ...
- 【高并发】通过源码深度分析线程池中Worker线程的执行流程
大家好,我是冰河~~ 在<高并发之--通过ThreadPoolExecutor类的源码深度解析线程池执行任务的核心流程>一文中我们深度分析了线程池执行任务的核心流程,在ThreadPool ...
- java使用Executor(执行器)管理线程
一.一个实现了Runnable接口的类 class MyThread implements Runnable{ private static int num = 0; @Override public ...
- Java自学-图形界面 Swing中的线程
Swing中的线程 步骤 1 : 三种线程 在Swing程序的开发中,需要建立3种线程的概念 初始化线程 初始化线程用于创建各种容器,组件并显示他们,一旦创建并显示,初始化线程的任务就结束了. 事件调 ...
- 《Java Concurrency》读书笔记,构建线程安全应用程序
1. 什么是线程安全性 调用一个函数(假设该函数是正确的)操作某对象常常会使该对象暂时陷入不可用的状态(通常称为不稳定状态),等到操作完全结束,该对象才会重新回到完全可用的状态.如果其他线程企图访问一 ...
- 【java并发】传统线程技术中创建线程的两种方式
传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...
- 深入浅出 Java Concurrency (27): 并发容器 part 12 线程安全的List/Set[转]
本小节是<并发容器>的最后一部分,这一个小节描述的是针对List/Set接口的一个线程版本. 在<并发队列与Queue简介>中介绍了并发容器的一个概括,主要描述的是Queue的 ...
- Java并发基础01. 传统线程技术中创建线程的两种方式
传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...
- Java Concurrency - ThreadFactory, 使用工厂方法创建线程
当需要创建多个类似的线程实例时,使用工厂模式替代 new 操作符创建线程,能使代码更为简洁,易于维护.JDK 提供了 java.util.concurrent.ThreadFactory 接口,Thr ...
随机推荐
- AfxGetMainWnd()函数用法
CWnd* AfxGetMainWnd( ); 使用AfxGetMainWnd函数获取MFC程序中的主框架类指针是一个常用作法. 就是获得应用程序主窗口的指针,AfxGetMainWnd()-> ...
- ios 移动应用通用逻辑流程
请先看前一篇文章<移动互联网app业务逻辑图>,以便于理解 http://blog.csdn.net/uxyheaven/article/details/14156659 1 start ...
- 漫谈云计算与SOA (1)
SOA是什么? 英语直译是基于服务的架构,就是一种技术框架,促使企业内部与外部所有相关的系统公开和访问定义良好的服务和绑定于服务的信息,进一步抽象成流程层和组合应用,从而构成解决方案. 说人话:重用服 ...
- .Net转前端
坚持 OR 方向 转前端,去折腾CSS JS 各种神奇的移动端框架: Web App H5 前端 前端工程师=javascript+N种技能,即一专多长: JavaScript 世界,Node.js, ...
- MEF 编程指南(十二):批量组合
MEF 容器实例并非不可变的.如果目录支持改变(像监控目录变动)或者在运行时添加/移除部件都可能发生改变.以前,你不得不做出改动并且调用 CompositionContainer 上的 Compose ...
- PC/UVa 题号: 110104/706 LC-Display (液晶显示屏)题解
#include <string> #include <iostream> #include <cstring> #include <algorithm> ...
- ArcObjects SDK(AE)10.1在vs2012安装的方法
ArcObjects SDK(以下简称AO)10.1只支持vs2010,如果装了vs2012,再安装AO会提示一串鸡肠(英文),意思是AO10.1只支持vs2010 想在2012下安装,可以通过修改注 ...
- SqlServer更新视图存储过程函数脚本
--视图.存储过程.函数名称 DECLARE @NAME NVARCHAR(255); --局部游标 DECLARE @CUR CURSOR --自动修改未上状态为旷课 SET @CUR=CURSOR ...
- Win7 不能安装 msi 解决办法
Win7 不能安装Setup.msi解决办法 解决方案如下: 新建一个文本文件,输入msiexec /i d:\Setup.msi (假设文件名为Setup.msi ,放在d盘根目录下,即是安装程序的 ...
- centos环境配置
1. centos上安装开发环境 yum groupinstall "Development Tools" "Legacy Software Development&qu ...