当前位置:网站首页>Future usage details
Future usage details
2022-04-23 17:36:00 【Flechazo`】
Future Usage details
Preface
Why does it appear Future Mechanism
Two common ways to create threads . One is direct inheritance Thread, The other is to realize Runnable Interface .
One drawback of both approaches is that : Unable to get execution result after task execution .
from Java 1.5 Start , Provided. Callable and Future, Through them, you can get the task execution result after the task execution .
Future The core idea of the pattern is to enable the main thread to use the time that it needs to wait synchronously to do other things .
Because the execution results can be obtained asynchronously , So you don't have to wait synchronously to get the execution result .
Future Usage details
It's easy to use
System.out.println(" main start ");
FutureTask<Integer> integerFutureTask = new FutureTask<>(new TestA());
new Thread(integerFutureTask).start();
System.out.println(" integerFutureTask ...");
Integer integer = integerFutureTask.get();
System.out.println(integer);
System.out.println(" main end ");
class TestA implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println(" call start ");
Thread.sleep(10000);
System.out.println(" call end ");
return 1;
}
}
get It will always block access
Of course, you can also set the timeout
public V get(long timeout, TimeUnit unit)
Future Simple principle
It's simple to use , Let's study the specific principle
We all know Thread Can only run Runable Interface
How does the return value return ?
FutureTask<Integer> integerFutureTask = new FutureTask<>(new TestA());
In this line of code, you can see FutureTask Realized RunnableFuture Interface
Continue to look at RunnableFuture The interface inherits our Runnable Interface And inherited a Future Interface
Future Interface
Defines some methods that return values
public interface Future<V> {
// Cancel
boolean cancel(boolean mayInterruptIfRunning);
// Whether to cancel
boolean isCancelled();
// Whether to carry out
boolean isDone();
// obtain
V get() throws InterruptedException, ExecutionException;
// Timeout to get
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
The principle and process are as follows
First step
Initialization task , Set thread state
We can see several states of the thread and some states from start to end
outcome Is the return value of the output
runner Indicates the running thread
waiters Indicates the waiting thread
The second step
run Method run
public void run() {
// Determine whether it is running
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
//
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// actual The bottom layer is still running call Interface
result = c.call();
// Running state
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
// Handling exceptions
setException(ex);
}
if (ran)
//c.call() At the end of the run , Set result
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
// If the thread is interrupted
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
The setting result sets the thread state to , Also set the value outcome
Third parts
get To get the results
You can see that when the state is not greater than or equal to COMPLETING It will block
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
// If the thread is interrupted
if (Thread.interrupted()) {
// Waiting to be removed from the queue
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
// Execution completed
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
// hand over cpu Executive power Re competition
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
// Next thread Wake up the
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
// Overtime
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
Return value Strong transition type
Thread pool return principle
Submit a return task with parameters
Submission code
Also to FutureTask To carry out
Custom return task value
You can refer to this to implement your own submission
Get data interface
public interface Future<T> {
T get() throws InterruptedException;
}
Do things interface
public interface FutureTask<T> {
T call();
}
Submit processing tasks asynchronously
public class FutureTaskService {
/** * Submit processing tasks asynchronously * @param futureTask * @param <T> * @return */
public <T> Future<T> submit(final FutureTask<T> futureTask){
// Asynchronous return
AysFutureTask<T> aysFutureTask = new AysFutureTask();
// Threads handle tasks
new Thread(()->{
// Perform tasks
T call = futureTask.call();
// Finish the task Notification return
aysFutureTask.done(call);
}).start();
// Asynchronous return
return aysFutureTask;
}
}
test
public class MainTest {
public static void main(String[] args) throws InterruptedException {
FutureTaskService futureTaskService = new FutureTaskService();
Future<String> submit = futureTaskService.submit(() -> {
// Submit tasks
return doThing();
});
System.out.println(" -------- return ------- ");
System.out.println(" --------- Do something else ----- ");
System.out.println(" --------- do other ----- ");
// obtain The task just submitted
System.out.println(submit.get());
}
/** * Simulate database reading and writing perhaps Network request * @return */
private static String doThing(){
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return " Do things ...";
}
}
test result
You can see the task we submitted first , Get the results after handling other things in front , During this period, the task is being carried out , Perform multiple tasks at the same time , Blocking the results at the last moment .
Last
FutureTask yes Future The concrete realization of .
FutureTask Realized RunnableFuture Interface .RunnableFuture The interface also inherits Future and Runnable Interface .
Thread You can submit FutureTask It's actually execution call Method
And then use cas Compare thread status and wait for results
Future Inheritance graph
Of course Future There are other extended uses , Such as CompletableFuture etc.
版权声明
本文为[Flechazo`]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231727205353.html
边栏推荐
- Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
- 386. Dictionary order (medium) - iteration - full arrangement
- [simple understanding of database]
- Read software engineering at Google (15)
- . net type transfer
- Construction of functions in C language programming
- QT modification UI does not take effect
- [WPF binding 3] listview basic binding and data template binding
- Shell-sed命令的使用
- Sword finger offer 22 The penultimate node in the linked list - speed pointer
猜你喜欢
Understanding of RPC core concepts
958. 二叉树的完全性检验
ASP. Net core JWT certification
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
How to change input into text
Exercise: even sum, threshold segmentation and difference (two basic questions of list object)
470. Rand10() is implemented with rand7()
Why do some people say SCM is simple and I have to learn it so hard?
RPC核心概念理解
PC电脑使用无线网卡连接上手机热点,为什么不能上网
随机推荐
嵌入式系统中,FLASH中的程序代码必须搬到RAM中运行吗?
双指针进阶--leetcode题目--盛最多水的容器
Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
Header built-in object
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
Open futures, open an account, cloud security or trust the software of futures companies?
386. 字典序排数(中等)-迭代-全排列
Compare the performance of query based on the number of paging data that meet the query conditions
198. Looting - Dynamic Planning
Metaprogramming, proxy and reflection
Input file upload
How to use the input table one-way service to send (occupy less) picture files (body transmission)? FileReader built-in object involved
Ring back to origin problem - byte jumping high frequency problem
Perception of linear algebra 2
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
[simple understanding of database]
JVM class loading mechanism
440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question
Why do some people say SCM is simple and I have to learn it so hard?
Future 用法详解