当前位置:网站首页>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
边栏推荐
- Software testing interview questions: How many types of software are there?
- lua 如何 实现一个unity协程的工具
- 《MySQL入门很轻松》第2章:MySQL管理工具介绍
- 【idea】idea配置sql格式化
- leetcode:267. 回文排列 II
- 《WEB安全渗透测试》(28)Burp Collaborator-dnslog外带技术
- 2022 The Third J Question Journey
- D - I Hate Non-integer Number (count of selected number dp
- node使用redis
- 英特尔WiFi 7产品将于2024年亮相 最高速度可达5.8Gbps
猜你喜欢
随机推荐
Software testing interview questions: the difference and connection between black box testing, white box testing, and unit testing, integration testing, system testing, and acceptance testing?
[230]连接Redis后执行命令错误 MISCONF Redis is configured to save RDB snapshots
node uses redis
僵尸进程和孤儿进程
Zombie and orphan processes
could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
【idea】idea配置sql格式化
数据类型及输入输出初探(C语言)
【论文笔记】—低照度图像增强—Unsupervised—EnlightenGAN—2019-TIP
软件测试面试题:请你分别画出 OSI 的七层网络结构图和 TCP/IP 的四层结构图?
2022杭电多校第三场 K题 Taxi
英特尔WiFi 7产品将于2024年亮相 最高速度可达5.8Gbps
Cloud native - Kubernetes 】 【 scheduling constraints
tiup update
2022多校第二场 K题 Link with Bracket Sequence I
测试经理要不要做测试执行?
tiup status
【unity编译器扩展之模型动画拷贝】
#yyds dry goods inventory #Switching equipment serious packet loss troubleshooting
SV class virtual method of polymorphism








