Various ways to implement asynchronous in Java
There are many ways to implement asynchronous processing in Java, each with its specific applicable scenarios and advantages and disadvantages. Here are several common ways to implement asynchronous processing:
1. Thread pool (ExecutorService)
-
Introduction:use
ExecutorService
A thread pool can be created to perform asynchronous tasks. - advantage: Resource reuse and thread management are convenient.
- shortcoming: The life cycle of the thread pool needs to be managed manually.
- Example:
import ; import ; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = (2); Runnable task1 = () -> { ("Task 1 running in thread: " + ().getName()); }; Runnable task2 = () -> { ("Task 2 running in thread: " + ().getName()); }; (task1); (task2); (); } }
2. CompletableFuture
-
Introduction:
CompletableFuture
It is a powerful asynchronous programming tool introduced in Java 8, supporting chain calls and combinatorial operations. - advantage: Rich features and easy to combine multiple asynchronous operations.
- shortcoming: The learning curve is steeper.
- Example:
import ; public class CompletableFutureExample { public static void main(String[] args) { (() -> { ("Task 1 running in thread: " + ().getName()); return "Result 1"; }).thenApply(result -> { ("Task 2 running in thread: " + ().getName()); return result + " processed"; }).thenAccept(finalResult -> { ("Final result: " + finalResult); }); // Prevent the main thread from ending early try { (1000); } catch (InterruptedException e) { (); } } }
3. ForkJoinPool
-
Introduction:
ForkJoinPool
It is a special thread pool, suitable for scenarios where it can be decomposed into multiple subtasks in parallel processing. - advantage: Suitable for handling large quantities of fine-grained tasks.
- shortcoming: Applicable to specific types of tasks, not all asynchronous scenarios.
- Example:
import ; import ; public class ForkJoinExample extends RecursiveTask<Integer> { private final int threshold = 2; private final int start; private final int end; public ForkJoinExample(int start, int end) { = start; = end; } @Override protected Integer compute() { if (end - start <= threshold) { int sum = 0; for (int i = start; i < end; i++) { sum += i; } return sum; } else { int middle = (start + end) / 2; ForkJoinExample subtask1 = new ForkJoinExample(start, middle); ForkJoinExample subtask2 = new ForkJoinExample(middle, end); (); (); return () + (); } } public static void main(String[] args) { ForkJoinPool pool = new ForkJoinPool(); ForkJoinExample task = new ForkJoinExample(1, 100); int result = (task); ("Result: " + result); } }
4. Callable and Future
-
Introduction:
Callable
is a task that can return results and may throw exceptions.Future
Used to obtainCallable
execution results. - advantage: You can get the execution result of the task.
- shortcoming: Need to manually manage threads and tasks' life cycles.
- Example:
import ; import ; import ; import ; import ; public class CallableFutureExample { public static void main(String[] args) { ExecutorService executor = (); Callable<Integer> task = () -> { (2000); return 42; }; Future<Integer> future = (task); try { Integer result = (); ("Result: " + result); } catch (InterruptedException | ExecutionException e) { (); } (); } }
5. ScheduledExecutorService
-
Introduction:
ScheduledExecutorService
It is a thread pool that can schedule delayed and periodic tasks. - advantage: Suitable for scheduled and periodic tasks.
- shortcoming: The function is relatively single.
- Example:
import ; import ; import ; public class ScheduledExecutorExample { public static void main(String[] args) { ScheduledExecutorService scheduler = (1); Runnable task = () -> { ("Task running in thread: " + ().getName()); }; // Execute tasks after 2 seconds delay (task, 2, ); // Execute tasks every 1 second (task, 0, 1, ); // Prevent the main thread from ending early try { (10000); } catch (InterruptedException e) { (); } (); } }
Summarize
- Thread pool (
ExecutorService
): Suitable for general asynchronous tasks. -
CompletableFuture
: Suitable for complex asynchronous operations and chain calls. -
ForkJoinPool
: Suitable for scenarios where it can be decomposed into multiple subtasks in parallel processing. -
Callable
andFuture
: Suitable for scenarios where task results need to be obtained. -
ScheduledExecutorService
: Suitable for timing and periodic tasks.
Selecting the appropriate asynchronous processing method according to specific needs can improve the performance and maintainability of the program. Hope these examples help you! If you have more questions or need further assistance, feel free to ask.
This is the end of this article about how to implement asynchronous in Java. For more related Java asynchronous content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
Understanding the life cycle of local variables in the perspective of assembly
This article mainly introduces the understanding of the life cycle of local variables from the perspective of detailed explanation of JVM. This article introduces you very detailedly and has certain reference value for your study or work. Friends who need it can refer to it.2020-07-07Java practical business library management system based on I/O stream design
This article mainly introduces the library management system based on I/O stream design in Java. There are very detailed code examples in the article, which are very helpful to friends who are learning Java. Friends who need it can refer to it.2021-04-04Analysis of parameter parameters problem cannot be parsed
This article introduces the parameter analysis problem that occurs when calling the interface in Spring Boot 3.2.1. This error is caused by the error checksum error prompt strengthened by the new version of Spring. After Spring 6.1, the official requirement that the parameter transmission in the URL must be declared using `@PathVariable` to declare the variable used for receiving, and the `@RequestParam` annotation cannot be omitted. Interested friends can take a look.2025-03-03A more detailed introduction to JNI
JNI is a native language programming interface. It allows Java code running in the JVM to interoperate with local code written in C, C++ or assembly. Below, through this article, let’s share with you the introduction of JNI. Interested friends will take a look2017-10-10Java simple text splitter implementation code
This article mainly introduces the implementation code of Java simple text splitter in detail, which has certain reference value. Interested friends can refer to it.2017-07-07Java memory release implementation code case
This article mainly introduces Java memory release implementation code cases. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.2020-12-12A brief explanation of the interpreter mode of Java design pattern programming
This article mainly introduces the explanation of the interpreter mode in Java design pattern programming. The interpreter design pattern should pay attention to the performance problems caused by it. Friends who need it can refer to it.2016-04-04Detailed explanation of examples that use static methods to return class names in JAVA development
This article mainly introduces the detailed explanation of the examples of returning class names by static methods in JAVA development. Here it mainly explains the use of exceptions to get class names. I hope it can help you. Friends who need it can refer to it.2017-08-08Java implementation examples of menu tree building
This article mainly introduces the implementation examples of Java building menu trees, such as first-level menus, second-level menus, third-level menus and even more levels of menus. The article introduces the example code in detail, which has certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.2023-05-05A brief discussion on Filter filter in Java
This article mainly introduces a brief discussion of Filter filters in Java. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor2017-02-02