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 ...
随机推荐
- 利用hashtable和time函数加速Lisp程序
程序功能是从一个英文文本中得到单词表,再得到押韵词表.即输出可能这样开始: a ameoeba alba samba marimba... 这样结束: ...megahertz gigahertz j ...
- CodeForces 706B Interesting drink (二分查找)
题意:给定 n 个数,然后有 m 个询问,每个询问一个数,问你小于等于这个数的数有多少个. 析:其实很简单么,先排序,然后十分查找,so easy. 代码如下: #pragma comment(lin ...
- C++中标准容器Vector,元素操作.insert()小结
insert() 函数有以下三种用法: iterator insert( iterator loc, const TYPE &val ); //在指定位置loc前插入值为val的元素,返回指 ...
- matlab eps中文乱码的解决方法
直接存成eps总是乱码 最优解决方法是matlab print 保存成jpg,之后用adobe acrobat pro 打开jpg文件另存为eps
- Spring Hibernate4 整合配置文档
1 applicationContext.xml配置文档 <?xml version="1.0" encoding="UTF-8"?><bea ...
- [JS 基础] touchEvent中的changedTouches,targetTouches和touches的区别
对于移动端开发中 touchEvent(触摸事件) 中changedTouches,targetTouches和touches的区别往往不容易弄清,故特意查询了 MDN相关资料 1. 其中,对 cha ...
- 实现CCLayer只显示一个矩形可见区域
转自:http://blog.csdn.net/while0/article/details/11004147 CCLayer的区域可能会比较大,怎样让它只显示其中一部分区域呢? 这个还是有很多场景 ...
- 嗯,记录一些eclipse的快捷键
alt+/:自动补全 ctrl+/:注释 // 再按一下取消注释 ctrl+shift+\:区块注释 /* */ ctrl+shift+\:取消区块注释 ctrl+shift+f:格式化代码 ctrl ...
- POJ1463:Strategic game(树形DP)
Description Bob enjoys playing computer games, especially strategic games, but sometimes he cannot f ...
- 将PHP作为Shell脚本语言使用
我们都知道.PHP是一种非常好的动态网页开发语言(速度飞快.开发周期短--).可是仅仅有非常少数的人意识到PHP也能够非常好的作为编写Shell脚本的语言,当PHP作为编写Shell脚本的语言时,他并 ...