当前位置:网站首页>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
边栏推荐
- 2022 Hangzhou Electric Power Multi-School Session 3 Question L Two Permutations
- ansible学习笔记分享-含剧本示例
- oracle创建表空间
- 机器学习(公式推导与代码实现)--sklearn机器学习库
- Cloud native - Kubernetes 】 【 scheduling constraints
- gorm的Raw与scan
- 2022 Hangzhou Electric Power Multi-School Session 3 K Question Taxi
- TinyMCE禁用转义
- 2022杭电多校第三场 K题 Taxi
- 标识符、关键字、常量 和变量(C语言)
猜你喜欢
[idea] idea configures sql formatting
node使用redis
STC89C52RC的P4口的应用问题
性能测试如何准备测试数据
leetcode:266. 回文全排列
《WEB安全渗透测试》(28)Burp Collaborator-dnslog外带技术
Metasploit-域名上线隐藏IP
The master teaches you the 3D real-time character production process, the game modeling process sharing
matlab 采用描点法进行数据模拟和仿真
Will domestic websites use Hong Kong servers be blocked?
随机推荐
2022 Multi-school Second Session K Question Link with Bracket Sequence I
Zombie and orphan processes
2022 Hangzhou Electric Power Multi-School Session 3 Question B Boss Rush
oracle创建用户
软件测试面试题:做好测试计划的关键是什么?
国内网站用香港服务器会被封吗?
GO中sync包自由控制并发的方法
what?测试/开发程序员要被淘汰了?年龄40被砍到了32?一瞬间,有点缓不过神来......
IDEA file encoding modification
Software Testing Interview Questions: Qualifying Criteria for Software Acceptance Testing?
The applicable scenarios and common product types of the KT148A electronic voice chip ic solution
Software Testing Interview Questions: What Are the Types of Software Testing?
找不到DiscoveryClient类型的Bean
软件质量评估的通用模型
MAUI Blazor 权限经验分享 (定位,使用相机)
软件测试面试题:软件验收测试的合格通过准则?
Mysql_13 事务
tiup status
tensor.nozero(), mask, [mask]
Software testing interview questions: What stages should a complete set of tests consist of?