当前位置:网站首页>Analysis of the use of JUC framework from runnable to callable to futuretask
Analysis of the use of JUC framework from runnable to callable to futuretask
2022-07-27 11:39:00 【anlian523】
Preface
This article aims to briefly explain Runnable、Callable、FutureTask These threads execute related interfaces and classes . For the back FutureTask Lay the groundwork for source code explanation .
Runnable
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
We know that there are two ways to create threads :
- override fall
ThreadOf run Method :
new Thread() {
@Override
public void run() {
int count = 0;
for(int i = 1;i <= 100;i++)
count += i;
}
}.start();
seen Thread We all know the source code , We call Thread#start() after , A new thread will be created to execute this Thread Of run Method . But the above executors and executors task Bound together , inflexible .
- Pass a
RunnableThe object is toThread:
new Thread(new Runnable(){
@Override
public void run() {
int count = 0;
for(int i = 1;i <= 100;i++)
count += i;
}
}).start();
such , By creating a Runnable Anonymous inner class object , Can achieve the same effect , But the executor and execution task Separated .
public class Thread implements Runnable {
/* What will be run. */
private Runnable target;
@Override
public void run() {
if (target != null) {
target.run();
}
}
}
from Thread Source code can be seen , When there is no override fall run When the method is used ,run Method will execute the held Runnable Object's run Method . To put it simply , It's dolls .
public class test5 {
public static Runnable task = new Runnable() {
@Override
public void run() {
int count = 0;
for(int i = 1;i <= 100;i++)
count += i;
}
};
public static void main(String[] args) throws InterruptedException {
new Thread(task).start();
new Thread(task).start();
}
}
The executor and the executor task Separation is good , The above example shows that two executors can execute the same task.
Callable
And Runnable comparison ,Callable There are some differences in the interface :
- Runnable Interface has no return value ,Callable Interface has a return value . And because the return value is generic , So any type of return value supports .
- Runnable Interface run There is no way
throws Exception. It means ,Runnable You can't throw an exception ( A subclass cannot throw more exceptions than its parent class , But now Runnable Of run The method itself does not throw any exceptions );Callable The interface can throw an exception .
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
But pay attention to ,Thread No constructor can accept Callable Parametric , and Thread None of them Callable Type member .
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
It seems that if you want to use Callable We have to rely on other things .
FutureTask
Answer the above questions first , Want to use Callable We have to rely on it FutureTask, Although I can't see it here for the time being FutureTask and Callable The relationship between .
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
Turned out to be FutureTask The constructor of can accept one Callable object , This links the two , and FutureTask Itself is another Runnable, This shows that FutureTask Pass to Thread The constructor of the object .
public class test5 {
public static void main(String[] args) throws InterruptedException {
FutureTask<Integer> result = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int count = 0;
for(int i = 1;i <= 100;i++)
count += i;
return count;
}
});
new Thread(result).start();
try {
System.out.println(result.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
/*output: 5050 */
The above example shows FutureTask Usage of , It seems that the thread passes FutureTask Object indirectly calls Callable Of call Method . Be careful , call result.get() The main thread will block for a while until call Method execution completed .
Although this class diagram is a little complicated , Actually RunnableFuture Will be Future and Runnable Just synthesize a new interface , But no new method is added .Runnable We have seen , have a look Future Well :
public interface Future<V> {
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
}
Future Designed to be available asynchronously task Interface of execution results .
get(). get task Execution results , If task It's done , Return the execution result immediately ; If task Not finished , Then block until the execution is completed .get(long timeout, TimeUnit unit). Timeout version of the previous function , Block until Execution completed or timed out .cancel(boolean mayInterruptIfRunning). Try to cancel task, The return value indicates that the cancellation operation is successful .isCancelled(). Judge a task It has been cancelled . Cancel must be task It was canceled before the execution was completed , It also includes being canceled without implementation .isDone(). If a task is over , Then return to true. return true There are three situations :normal termination. Normal execution completed .an exception. The execution process throws an exception .cancellation.task Be cancelled .
Of course , Generally, we use it with thread pool Callable:
package com.xxx.future;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class BlockingTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
final ExecutorService service = Executors.newFixedThreadPool(5);
Future<String> result = service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// Simulate the asynchronous process in reality , Wait five seconds to return the result
Thread.sleep(1000*5);
return "ok";
}
});
System.out.println("task begin...");
// If the thread does not complete execution , So keep waiting , Feel the thread execution process intuitively by printing information
while(!result.isDone()){
System.out.println("wait for 1 second");
Thread.sleep(1000);
}
String ok = result.get();
service.shutdown();
System.out.println("task end "+ok);
}
}
But in fact, the practice of thread pool is also to construct a FutureTask.
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
边栏推荐
- 剑指 Offer 笔记: T58 - I. 翻转单词顺序
- 多家银行调整现金管理类理财产品申赎规则:申赎确认时效“T+0”变“T+1”
- 【无标题】多模态模型 CLIP
- When std:: bind meets this
- The C programming language (2nd) -- Notes -- 1.10
- Kepserver configuration
- Moveit2 -- 2. Quick start of moveit in rviz
- Solutions to errors in tensorflow operation
- [unity entry program] creator kitfps: first person shooting 3D game
- Codeforces round #664C
猜你喜欢

Game theory acwing 891. Nim game

Win10 vscode code code format setting and remote breakpoint debugging

Memory search acwing 901. Skiing

EfficientNet

origin如何作一张图中多张子图是柱状图(或其他图)

Kepserver configuration

Could not load dynamic library ‘libcudnn.so.8‘;

Modelarts voice detection and text classification

The C programming language (2nd) -- Notes -- 1.6

Modelarts image classification and object detection
随机推荐
美现首例孕妇猴痘病例:新生儿被注射免疫球蛋白,已安全出生
LeetCode 01: T1. 两数之和 ; T1108. IP 地址无效化 ; T344. 反转字符串
Tensorflow tensor operation function set
Basic use of cmake
你真的会写二分查找吗——变种二分查找
The C programming language-2nd-- notes -- 4.11.3
What is private traffic?
第7章 异常处理
LAN SDN hard core technology insider 25 looking forward to the future - RDMA (Part 2)
箱型图介绍
Summary of C language knowledge involved in learning STM32F103 (link only)
SQL statement learning and the use of pymysql
Raw socket grabs packets, and packets on some ports cannot be caught
zabbix自定义监控项
微商的差商近似
Memory search acwing 901. Skiing
(9) Shell I / O redirection
新版数据仓库的同步使用参考(新手向)
局域网SDN技术硬核内幕 13 从局域网到互联网
Keil MDK编译出现..\USER\stm32f10x.h(428): error: #67: expected a “}“错误的解决办法