当前位置:网站首页>[high concurrency] 28000 words' summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little drifting (middle)
[high concurrency] 28000 words' summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little drifting (middle)
2022-06-29 13:57:00 【Hua Weiyun】
Hello everyone , I'm glacier ~~
stay Java In multithreading programming , except Thread Classes and Runnable Outside the interface , It has to be said that Callable Interface Future The interface . Using inheritance Thread Class or implementation Runnable Thread of interface , Unable to return final execution result data , Can only wait for thread execution to complete . here , If you want to get the return result of thread execution , that ,Callable and Future That comes in handy .
notes : The whole process of the article is high energy , Recommended collection , If the article helps you a little , Guys, one button three times , Thank you very much! ~~
Two asynchronous models and deep parsing Future Interface
Two asynchronous models
stay Java In concurrent programming , In general, there are two asynchronous programming models , One is to run other tasks asynchronously in parallel , There is no need to return the result data of the task . One is to run other tasks asynchronously , Need to return results .
1. Asynchronous model with no return results
Asynchronous tasks that return no results , You can drop a task directly into a thread or thread pool to run , here , Unable to directly obtain the execution result data of the task , One way is to use the callback method to get the running result of the task .
The specific plan is : Define a callback interface , The method of receiving task result data is defined in the interface , The specific logic is completed in the implementation class of the callback interface . Put the callback interface and task parameters into the thread or thread pool to run , The interface method is called after the task is run , Execute the logic in the callback interface implementation class to process the result data . here , Give a simple example for reference .
- Define callback interface
package io.binghe.concurrent.lab04;/** * @author binghe * @version 1.0.0 * @description Define callback interface */public interface TaskCallable<T> { T callable(T t);}General purpose for easy interface , Generics are defined here for callback interfaces .
- Define the encapsulation class of task result data
package io.binghe.concurrent.lab04;import java.io.Serializable;/** * @author binghe * @version 1.0.0 * @description Task execution results */public class TaskResult implements Serializable { private static final long serialVersionUID = 8678277072402730062L; /** * Task status */ private Integer taskStatus; /** * Mission message */ private String taskMessage; /** * Task result data */ private String taskResult; // Omit getter and setter Method @Override public String toString() { return "TaskResult{" + "taskStatus=" + taskStatus + ", taskMessage='" + taskMessage + '\'' + ", taskResult='" + taskResult + '\'' + '}'; }}- Create an implementation class for the callback interface
The implementation class of callback interface is mainly used to process the returned results of tasks , here , For the convenience of demonstration , Just return the result data to . We need to do the corresponding analysis and processing according to the specific business scenarios .
package io.binghe.concurrent.lab04;/** * @author binghe * @version 1.0.0 * @description Implementation class of callback function */public class TaskHandler implements TaskCallable<TaskResult> { @Overridepublic TaskResult callable(TaskResult taskResult) {//TODO After getting the result data, further processing System.out.println(taskResult.toString()); return taskResult; }}- Create the execution class of the task
The execution class of a task is the class that performs a specific task , Realization Runnable Interface , Define a member variable of callback interface type and a String Task parameters of type ( The parameters of the simulation task ), The callback interface and task parameters are injected into the construction method . stay run Method , After the task is completed, encapsulate the result data of the task into TaskResult object , The method that calls the callback interface will TaskResult Object to the callback method .
package io.binghe.concurrent.lab04;/** * @author binghe * @version 1.0.0 * @description Task execution class */public class TaskExecutor implements Runnable{ private TaskCallable<TaskResult> taskCallable; private String taskParameter; public TaskExecutor(TaskCallable<TaskResult> taskCallable, String taskParameter){ this.taskCallable = taskCallable; this.taskParameter = taskParameter; } @Override public void run() { //TODO A series of business logic , Encapsulate the result data into TaskResult Object and return TaskResult result = new TaskResult(); result.setTaskStatus(1); result.setTaskMessage(this.taskParameter); result.setTaskResult(" Asynchronous callback successful "); taskCallable.callable(result); }}Come here , The whole big frame is finished , Next , It's testing to see if you can get the results of asynchronous tasks .
- Asynchronous task test class
package io.binghe.concurrent.lab04;/** * @author binghe * @version 1.0.0 * @description Test callback */public class TaskCallableTest { public static void main(String[] args){ TaskCallable<TaskResult> taskCallable = new TaskHandler(); TaskExecutor taskExecutor = new TaskExecutor(taskCallable, " Test the callback task "); new Thread(taskExecutor).start(); }}In the test class , Use Thread Class to create a new thread , And start the thread to run the task . The final interface data of the running program is as follows .
TaskResult{taskStatus=1, taskMessage=' Test the callback task ', taskResult=' Asynchronous callback successful '}You can savor this way to get asynchronous results . here , It's just a simple use of Thread Class to create and start a thread , You can also use thread pool to implement . You can get asynchronous results through callback interface in the way of thread pool .
2. Asynchronous models with returned results
Although using callback interface can get the result of asynchronous task , But it's a little more complicated to use . stay JDK Provides a processing scheme that can directly return asynchronous results . The most common is to use Future Interface or its implementation class FutureTask To receive the return result of the task .
- Use Future Interface to get asynchronous results
Use Future Interfaces often cooperate with thread pools to obtain asynchronous execution results , As shown below .
package io.binghe.concurrent.lab04;import java.util.concurrent.*;/** * @author binghe * @version 1.0.0 * @description test Future Get asynchronous results */public class FutureTest { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { return " test Future Get asynchronous results "; } }); System.out.println(future.get()); executorService.shutdown(); }}The running results are as follows .
test Future Get asynchronous results - Use FutureTask Class to get asynchronous results
FutureTask Class can combine Thread Class can also be used in combination with thread pool , Next , Let's take a look at these two ways of use .
combination Thread An example of using the class is as follows .
package io.binghe.concurrent.lab04;import java.util.concurrent.*;/** * @author binghe * @version 1.0.0 * @description test FutureTask Get asynchronous results */public class FutureTaskTest { public static void main(String[] args)throws ExecutionException, InterruptedException{ FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() { @Override public String call() throws Exception { return " test FutureTask Get asynchronous results "; } }); new Thread(futureTask).start(); System.out.println(futureTask.get()); }}The running results are as follows .
test FutureTask Get asynchronous results An example of using thread pool is as follows .
package io.binghe.concurrent.lab04;import java.util.concurrent.*;/** * @author binghe * @version 1.0.0 * @description test FutureTask Get asynchronous results */public class FutureTaskTest { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() { @Override public String call() throws Exception { return " test FutureTask Get asynchronous results "; } }); executorService.execute(futureTask); System.out.println(futureTask.get()); executorService.shutdown(); }}The running results are as follows .
test FutureTask Get asynchronous results You can see the use of Future Interface or FutureTask Class to get asynchronous results is much easier than using callback interface to get asynchronous results . Be careful : There are many ways to achieve asynchrony , This is just an example of multithreading .
Next , Let's make a deep analysis Future Interface .
边栏推荐
- C language__ VA_ ARGS__ Usage of
- mysql函数和约束
- Deecamp2022 officially opened! Likaifu and zhangyaqin personally teach master courses 𞓜 innovation
- koa2+better-sqlite3实现增删改查
- Summary of common MySQL statements and commands
- What if the excel table exported from the repair record is too large?
- Online text filter less than specified length tool
- 韩国AI团队抄袭震动学界!1个导师带51个学生,还是抄袭惯犯
- Openssl证书工具使用手册
- 高校女生穿旗袍答辩!网友:导师说论文要是和旗袍一样漂亮就好了
猜你喜欢

华为机器学习服务语音识别功能,让应用绘“声”绘色

嵌入式开发:硬件在环测试
![[untitled] error in installation dependency: refusing to install package with name](/img/53/8c871037b7586343fd509dcecb0d96.png)
[untitled] error in installation dependency: refusing to install package with name "* * *" under a package

OpenSSL certificate tool user manual

CVPR上百人中招新冠,emoji成“呈堂证供”,M2 MBP被曝硬盘降速,今日更多大新闻在此...

Imile uses Zadig's multi cloud environment to deploy thousands of times a week to continuously deliver global business across clouds and regions

Uncover the secret! Pay attention to those machines under the membership system!

【系统设计】邻近服务

【云驻共创】通过Rust语言计算加速技术突破图片识别性能瓶颈

Cisco simulator simple campus network design, final assignment difficulty
随机推荐
Huawei machine learning service speech recognition function enables applications to paint "sound" and color
Cloud native (31) | kubernetes chapter kubernetes platform basic pre installed resources
在线文本过滤小于指定长度工具
C language__ VA_ ARGS__ Usage of
mysql函数和约束
CVPR上百人中招新冠,emoji成“呈堂证供”,M2 MBP被曝硬盘降速,今日更多大新闻在此...
Seekg() [easy to understand]
WinDbg debugging tool introduction
golang7_TCP编程
【无标题】安装依赖报错:Refusing to install package with name “***“ under a package
Windbg常用命令详解
[cloud resident co creation] break through the performance bottleneck of image recognition through rust language computing acceleration technology
*Clock in algorithm *leetcode 146 Analysis of LRU cache algorithm
MySQL 1146 error [easy to understand]
Source code migration from X86 platform to Kunpeng platform based on Kunpeng development kit [play with Huawei cloud]
昨天面试居然聊了半个多小时的异常处理
深度学习的坎坷六十年
中康控股开启招股:拟募资净额3.95亿港元,预计7月12日上市
Follow me study hcie big data mining Chapter 1 Introduction to data mining module 2
Application of ansvc reactive power compensation device in a shopping mall in Hebei