当前位置:网站首页>Get the thread return value. Introduction to the use of future interface and futuretask class
Get the thread return value. Introduction to the use of future interface and futuretask class
2022-04-23 14:14:00 【pureluckyfish】
Start a thread , Computer according to cpu And memory usage , Execute code in the thread at a future point in time . How do I know if the thread execution is complete , What's the result ?Future English means “ future 、 Future ”, seeing the name of a thing one thinks of its function Future Interface came into being .
One 、Future The interface is introduced
Usage method get Search , Block if necessary , Until it's ready .cancel Cancel the operation . Other methods are provided to determine whether the task is completed normally or cancelled . Once the calculation is done , We can't cancel the calculation . If used for cancellability Future, But do not provide available results , It can be stated that Future>, And back to null As a result of the underlying task .
Return value | Method name | Method usage description |
boolean | cancel(boolean mayInterruptIfRunning) | Attempt to cancel the execution of this task . If the task has been completed 、 Has been cancelled or cannot be cancelled for other reasons , Then the attempt will fail . If it works , And calling cancel The task did not start when , The task should never run . If the task has been started , be mayInterruptIfRunning Parameter determines whether the thread executing the task should be interrupted to try to stop the task |
boolean | isCancelled() | If this task is cancelled before normal completion , Then return to true |
boolean | isDone() | If this task is completed, return to true |
V | get() | Get thread execution results , Will be waiting , Until the thread execution is complete |
V | get(long timeout, TimeUnit unit) | Get thread execution results , If no result is obtained within the specified time, an exception will be thrown |
Two 、Future Code example
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class Future_FutureTask {
// Creating a thread pool
ExecutorService exec = Executors.newCachedThreadPool();
@Test
public void FutureTest() throws Exception {
// return Future
Future<?> future = exec.submit(() -> {
System.out.println("Runnabel Interface , No return value ");
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (future.isDone()) {
System.out.println(" Get thread return result :" + future.get());
} else {
System.out.println(" Get thread return result :" + future.get(10L, TimeUnit.SECONDS));
}
System.out.println(" Whether the thread is cancelled " + future.isCancelled());
}
}
3、 ... and 、FutureTask Introduction to implementation class
This class provides Future The basic implementation of the interface ;FutureTask Can be used to package into Callable
perhaps Runnable
Object to use . because FutureTask Realized Runnable Interface , therefore FutureTask Can be submitted to Executor perform
Four 、FutureTask Code example
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class Future_FutureTask {
// Creating a thread pool
ExecutorService exec = Executors.newCachedThreadPool();
@Test
public void FutureTaskTest() throws Exception {
// Use Lambda Create objects using expressions
// FutureTask<V> futureTask = new FutureTask<V>(Callable<V> callable)
FutureTask<String> futureTask = new FutureTask<String>(() -> {
return "FutureTask Introduction ";
});
exec.execute(futureTask);
System.out.println(" obtain FutureTask Return result of :" + futureTask.get());
}
}
5、 ... and 、 summary
Future Express Asynchronous computation ( Threads ) Result . The method provided is used to check whether the calculation is completed 、 Wait for it to complete and retrieve the results of the calculation .
FutureTask Class is Future Implementation class of interface
版权声明
本文为[pureluckyfish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231406486464.html
边栏推荐
- VMware 15pro mounts the hard disk of the real computer in the deepin system
- 文字组合,不重复,做搜索或查询关键字匹配
- ActiveMq基础知识
- Some experience of using dialogfragment and anti stepping pit experience (getactivity and getdialog are empty, cancelable is invalid, etc.)
- RobotFramework 之 用例执行
- Jmeter安装教程以及我遇到的问题的解决办法
- 服务器日志分析工具(识别,提取,合并,统计异常信息)
- RecyclerView高级使用(二)-垂直拖拽排序的简单实现
- pthread_ Why does self() repeat
- On the multi-level certificate based on OpenSSL, the issuance and management of multi-level Ca, and two-way authentication
猜你喜欢
随机推荐
Wechat applet communicates with low-power Bluetooth - receives data sent by hardware (IV)
Multiple inheritance virtual base exercises
RobotFramework 之 公共变量
连接公司跳板机取别名
星界边境文本自动翻译机使用说明
redis数据库讲解二(redis高可用、持久化、性能管理)
云迁移的六大场景
VMware 15pro mounts the hard disk of the real computer in the deepin system
HyperBDR云容灾V3.3.0版本发布|容灾功能升级,资源组管理功能优化
多云数据流转?云上容灾?年前最后的价值内容分享
帆软报表设置单元格填报以及根据值的大小进行排名方法
DeepinV20安装Mariadb
About the configuration and use of json5 in nodejs
MYSQL 主从同步避坑版教程
微信小程序客服接入,实现发送和接收消息
Gartner预测云迁移规模大幅增长;云迁移的优势是什么?
Date的after时间判断
mysql查询库大小
关于NodeJS中JSON5的相关配置和使用
帆软实现一个单选按钮,可以统一设置其他单选按钮的选择状态