当前位置:网站首页>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
边栏推荐
- 软件开发工具的技术要素
- About I double-checked and reviewed the About staff page, returning an industry question
- tiup telemetry
- 软件测试面试题:测试生命周期,测试过程分为几个阶段,以及各阶段的含义及使用的方法?
- 软件测试面试题:您如何看待软件过程改进?在您曾经工作过的企业中,是否有一些需要改进的东西呢?您期望的理想的测试人员的工作环境是怎样的?
- MAUI Blazor 权限经验分享 (定位,使用相机)
- redis可视化管理软件Redis Desktop Manager2022
- tiup uninstall
- 2022杭电多校 第三场 B题 Boss Rush
- Software testing interview questions: What are the three modules of LoadRunner?
猜你喜欢

数据类型及输入输出初探(C语言)

oracle创建表空间

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

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

Countdown to 1 day!From August 2nd to 4th, I will talk with you about open source and employment!

【idea】idea配置sql格式化

国内网站用香港服务器会被封吗?

翁恺C语言程序设计网课笔记合集

node使用redis

TinyMCE disable escape
随机推荐
软件测试面试题:请你分别画出 OSI 的七层网络结构图和 TCP/IP 的四层结构图?
软件测试面试题:您如何看待软件过程改进?在您曾经工作过的企业中,是否有一些需要改进的东西呢?您期望的理想的测试人员的工作环境是怎样的?
2022 Hangzhou Electric Multi-School 1004 Ball
关于我仔细检查审核过关于工作人员页面,返回一个所属行业问题
tiup status
tiup uninstall
QSunSync Qiniu cloud file synchronization tool, batch upload
leetcode:266. 回文全排列
软件测试面试题:测试生命周期,测试过程分为几个阶段,以及各阶段的含义及使用的方法?
uinty lua 关于异步函数的终极思想
软件测试面试题:做好测试计划的关键是什么?
进程间通信和线程间通信
2022杭电多校第一场 1004 Ball
2022 Nioke Multi-School Training Session 2 J Question Link with Arithmetic Progression
D - I Hate Non-integer Number (选数的计数dp
Software testing interview questions: What are the seven-layer network protocols?
怎样进行在不改变主线程执行的时候,进行日志的记录
标识符、关键字、常量 和变量(C语言)
倒计时1天!8月2日—4日与你聊聊开源与就业那些事!
软件测试面试题:网络七层协仪具体?