当前位置:网站首页>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
边栏推荐
- 第四届“传智杯”全国大学生IT技能大赛(决赛B组) 题解
- redis数据库讲解(四)主从复制、哨兵、Cluster群集
- Wechat applet communicates with esp8266 based on UDP protocol
- 政务云迁移实践 北明数科使用HyperMotion云迁移产品为某政府单位实施上云迁移项目,15天内完成近百套主机迁移
- mysql 5.1升级到5.69
- Detailed tutorial on the use of smoke sensor (mq-2) (based on raspberry pie 3B +)
- jsp学习3
- 帆软中需要设置合计值为0时,一整行都不显示的解决办法
- findstr不是内部或外部命令解决方法
- 帆软分割求解:一段字符串,只取其中某个字符(所需要的字段)
猜你喜欢
随机推荐
RobotFramework 之 公共变量
MySQL数据库讲解(七)
星界边境文本自动翻译机使用说明
Recyclerview advanced use (II) - simple implementation of vertical drag and drop sorting
VMWare安装64位XP中文教程
void*是怎样的存在?
mysql 5.1升级到5.67
Wechat applet positioning and ranging through low-power Bluetooth device (2)
Wechat applet communicates with esp8266 based on UDP protocol
Can I compile the header file and source file of the template separately
关于NodeJS中JSON5的相关配置和使用
Logback logger and root
How QT designer adds resource files
On September 8, the night before going to Songshan Lake
关于训练过程中损失函数出现断崖式增长的问题
帆软调用动态传参的方法,在标题中设置参数
Some good articles on pthread multithreading
帆软实现分页时第一行和最后两行冻结方式
redis数据库讲解二(redis高可用、持久化、性能管理)
数据库DbVisualizer Pro报文件错误,导致数据连接失败