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 ...
随机推荐
- UVa10562 Undraw the Trees
注意点: 空树情况处理. >= && buf[r+][i-]=='-') i--; #include<cstdio> #include<cstring> ...
- 【转】Rails 3.1错误-Could not find a JavaScript runtime及execjs和therubyracer介绍
转自:http://rubyer.me/blog/740/ Rails 3.1错误 /gems/execjs-1.1.2/lib/ execjs/runtimes.rb:43:in `autodete ...
- Android应用之《宋词三百首》(二)
接上回,上回我们讲到MainActivity里面将所有的宋词标题和作者显示到界面的ListView中去,我们接下来的工作是通过点击ListView的Item跳转到ContentActivity里面去显 ...
- SPOJ LIS2 Another Longest Increasing Subsequence Problem 三维偏序最长链 CDQ分治
Another Longest Increasing Subsequence Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://a ...
- Base64 图片转换工具
以前在写asp的后台的时候,有一个上传功能是必须的,那时候进行的图片预览(未上传前)其实就是获取本地的图片路径来显示图片,但是随着HTML5的出现,可以把图片通过编码来实现预览. 在雅虎的36条速度优 ...
- password安全之动态盐
首先,我们看看什么是盐:http://zh.wikipedia.org/zh/%E7%9B%90_%28%E5%AF%86%E7%A0%81%E5%AD%A6%29 ,再MD5是d16e970d6e5 ...
- material-dialogs
https://github.com/afollestad/material-dialogs
- Unable to automatically debug "XXXXX“
I solved this issue by going to C:\Program Files\Microsoft VisualStudio10.0\Common7\IDE then running ...
- Metadata Lock原理4
http://blog.chinaunix.net/uid-28212952-id-3400571.html Alibaba 今天发生一个故障,MM复制结构(主备库),备库slave del ...
- printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf - 输出格式转换函数
参考:http://blog.sina.com.cn/s/blog_674b5aae0100prv3.html 总览 (SYNOPSIS) #include <stdio.h> int p ...