当前位置:网站首页>JUC thread pool (1): FutureTask use
JUC thread pool (1): FutureTask use
2022-08-05 00:33:00 【learned mindset】
Future 表示了一个任务的生命周期,is a cancelable asynchronous operation,It's done at some point in the future,并提供对其结果的访问.
Many asynchronous task classes in the concurrent package inherit from Future,其中最典型的就是 FutureTask.
一. FutureTask简介
FutureTask常用来封装 Callable 和 Runnable ,也可以作为一个任务提交到线程池中执行.
FutureThe thread safety hasCAS保证.
FutureTask实现了Future的基础功能,如获取任务执行结果(get)和取消任务(cancel)等.If the task has not completed, it will block when the task execution result is obtained.
二. 使用案例
通过FutureTask封装Callable实现,The state of the thread can be obtained at runtime(是否运行完)、也可以取消任务,The result can be obtained when the run is complete,There are two ways to run a thread:
- 线程池运行futureTask
- Thread线程运行futureTask
public class CallDemo {
public static void main(String[] args) {
/** * * 方式1 : 线程池运行futureTask(futureTask包装的callable接口,futureTaskThe execution result can be obtained). * * 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
边栏推荐
- leetcode:266. 回文全排列
- 软件测试面试题:设计测试用例时应该考虑哪些方面,即不同的测试用例针对那些方面进行测试?
- 电子行业MES管理系统的主要功能与用途
- 网站最终产品页使用单一入口还是多入口?
- 2022杭电多校第一场 1004 Ball
- "Relish Podcast" #397 The factory manager is here: How to use technology to empower the law?
- what?测试/开发程序员要被淘汰了?年龄40被砍到了32?一瞬间,有点缓不过神来......
- E - Many Operations (bitwise consideration + dp thought to record the result after the operation
- 2022 Nioke Multi-School Training Session H Question H Take the Elevator
- How to automatically push my new articles to my fans (very simple, can't learn to hit me)
猜你喜欢

机器学习(公式推导与代码实现)--sklearn机器学习库

倒计时1天!8月2日—4日与你聊聊开源与就业那些事!

Cloud native - Kubernetes 】 【 scheduling constraints

matlab中rcosdesign函数升余弦滚降成型滤波器

子连接中的参数传递

电赛必备技能___定时ADC+DMA+串口通信
![[Cloud Native--Kubernetes] Pod Controller](/img/e1/1a8cc82223f9a9be79ebbf1211e9a4.png)
[Cloud Native--Kubernetes] Pod Controller

测试经理要不要做测试执行?

2022 Hangzhou Electric Power Multi-School Session 3 K Question Taxi

Mysql_14 存储引擎
随机推荐
could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
gorm的Raw与scan
软件基础的理论
软件质量评估的通用模型
canvas 高斯模糊效果
tiup update
2022牛客多校第三场 J题 Journey
关于我仔细检查审核过关于工作人员页面,返回一个所属行业问题
在线中文姓名生成工具推荐
lua 如何 实现一个unity协程的工具
2022杭电多校第一场 1004 Ball
QSunSync Qiniu cloud file synchronization tool, batch upload
SV 类的虚方法 多态
MongoDB搭建及基础操作
The applicable scenarios and common product types of the KT148A electronic voice chip ic solution
2022牛客多校训练第二场 H题 Take the Elevator
leetcode: 267. Palindromic permutations II
数据类型及输入输出初探(C语言)
MAUI Blazor 权限经验分享 (定位,使用相机)
Software Testing Interview Questions: What is Software Testing?The purpose and principle of software testing?