当前位置:网站首页>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;
}
边栏推荐
- Ask the big guys, is there transaction control for using flick sink data to MySQL? If at a checkpoint
- Digital triangle model acwing 1018. Minimum toll
- Newton-Raphson迭代法
- LAN SDN technology hard core insider 13 from LAN to Internet
- LeetCode 02: 剑指 Offer 58 - I. 翻转单词顺序(简单); T123. 验证回文串 ; T9. 回文数
- Wilcoxon rank-sum 和 signed-rank
- IDEA: Can‘t use Subversion command line client:svn 解决方案
- Redis simple to use
- Memory search acwing 901. Skiing
- 微机和单片机的区别
猜你喜欢

Stack acwing 3302. Expression evaluation

Game theory acwing 894. Split Nim game

Chinese remainder theorem acwing 204. strange way of expressing integers

Solve importerror: cannot import name'abs'import tensorflow error

【无标题】多模态模型 CLIP

Redis simple to use

什么是私域流量?

Maker harmony OS application development training notes 01

82. (cesium home) cesium points move on 3D models

暂用 Solo,博客选择困难
随机推荐
CTF crypto RSA getting started
第7章 异常处理
剑指 Offer 笔记: T58 - II. 左旋转字符串
makefile模板
Knapsack problem acwing 9. grouping knapsack problem
容斥原理 AcWing 890. 能被整除的数
Moveit2 - 5. Scenario Planning
WGet warning: unable to verify
[shader realizes shake random shaking effect _shader effect Chapter 10]
The C programming language (2nd) -- Notes -- 1.8
Why choose smart TV?
Moveit2 - 4. robot model and robot state
The C programming language-2nd-- notes -- 4.11.3
剑指 Offer 笔记: T39. 数组中出现次数超过一半的数字
LeetCode 02: 剑指 Offer 58 - I. 翻转单词顺序(简单); T123. 验证回文串 ; T9. 回文数
局域网SDN技术硬核内幕 11 云网融合CP的关键——层次化端口绑定
Keil MDK编译出现..\USER\stm32f10x.h(428): error: #67: expected a “}“错误的解决办法
The C programming language -- (2nd) -- Notes -- 4.11.2
N ¨UWA: Visual Synthesis Pre-training for Neural visUal World creAtionChenfei
The C programming language (2nd) -- Notes -- 1.9