当前位置:网站首页>JUC线程池(一): FutureTask使用
JUC线程池(一): FutureTask使用
2022-08-05 00:23:00 【学到的心态】
Future 表示了一个任务的生命周期,是一个可取消的异步操作,它在未来的某个时刻完成,并提供对其结果的访问。
并发包中许多异步任务类都继承自Future,其中最典型的就是 FutureTask。
一. FutureTask简介
FutureTask常用来封装 Callable 和 Runnable ,也可以作为一个任务提交到线程池中执行。
Future的线程安全有CAS保证。
FutureTask实现了Future的基础功能,如获取任务执行结果(get)和取消任务(cancel)等。如果任务尚未完成获取任务执行结果时会堵塞。
二. 使用案例
通过FutureTask封装Callable实现,运行时可以获取线程的状态(是否运行完)、也可以取消任务,运行完成可以获取结果,对于线程运行可以有以下两种方式:
- 线程池运行futureTask
- Thread线程运行futureTask
public class CallDemo {
public static void main(String[] args) {
/** * * 方式1 : 线程池运行futureTask(futureTask包装的callable接口,futureTask可以拿到执行结果)。 * * FutureTask + ExecutorService: * * ExecutorService executor = Executors.newCachedThreadPool(); * Task task = new Task(); * FutureTask<Integer> futureTask = new FutureTask<Integer>(task); * executor.submit(futureTask); * executor.shutdown(); */
/** * 方式2 : 线程运行futureTask * FutureTask + Thread */
// 2. 新建FutureTask,需要一个实现了Callable接口的类的实例作为构造函数参数
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyTask());
// 3. 新建Thread对象并启动
Thread thread = new Thread(futureTask);
thread.setName("Task thread");
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread [" + Thread.currentThread().getName() + "] is running");
// 4. 调用isDone()判断任务是否结束
if (!futureTask.isDone()) {
System.out.println("Task is not done");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int result = 0;
try {
// 5. 调用get()方法获取任务结果,如果任务没有执行完成则阻塞等待
result = futureTask.get();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("result is " + result);
}
// 1. 继承Callable接口,实现call()方法,泛型参数为要返回的类型
static class MyTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("Thread [" + Thread.currentThread().getName() + "] is running");
int result = 0;
for (int i = 0; i < 100; ++i) {
result += i;
}
Thread.sleep(3000);
return result;
}
}
}
三. FutureTask原理
FutureTask的类关系
FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable和Future接口,所以FutureTask既能作为Runnable被Thread使用,也可以作为 Future 用来得到计算结果。
参考:
https://pdai.tech/md/java/thread/java-thread-x-juc-executor-FutureTask.html
边栏推荐
- E - Many Operations (bitwise consideration + dp thought to record the result after the operation
- What is next-generation modeling (with learning materials)
- Software testing interview questions: What is the difference between load testing, capacity testing, and strength testing?
- 软件测试面试题:一套完整的测试应该由哪些阶段组成?
- 2022牛客多校训练第二场 H题 Take the Elevator
- leetcode: 266. All Palindromic Permutations
- 《MySQL入门很轻松》第2章:MySQL管理工具介绍
- E - Distance Sequence (前缀和优化dp
- ARC129E Yet Another Minimization 题解 【网络流笔记】
- The master teaches you the 3D real-time character production process, the game modeling process sharing
猜你喜欢
随机推荐
The master teaches you the 3D real-time character production process, the game modeling process sharing
Raw and scan of gorm
could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
QSunSync 七牛云文件同步工具,批量上传
tiup telemetry
僵尸进程和孤儿进程
MAUI Blazor 权限经验分享 (定位,使用相机)
Zombie and orphan processes
倒计时1天!8月2日—4日与你聊聊开源与就业那些事!
软件开发工具的技术要素
2022牛客多校第三场 J题 Journey
电赛必备技能___定时ADC+DMA+串口通信
软件测试面试题:您如何看待软件过程改进?在您曾经工作过的企业中,是否有一些需要改进的东西呢?您期望的理想的测试人员的工作环境是怎样的?
ansible学习笔记分享-含剧本示例
Software Testing Interview Questions: What's the Key to a Good Test Plan?
gorm joint table query - actual combat
导入JankStats检测卡帧库遇到问题记录
软件测试面试题:做好测试计划的关键是什么?
[LeetCode] Summary of Matrix Simulation Related Topics
canvas Gaussian blur effect