Junior — Middle
What tools and constructs are used in Java Core to implement asynchronous programming?
sobes.tech AI
Answer from AI
In Java Core, the following tools are used for asynchronous programming:
- Thread — the basic class for creating and managing threads.
- Runnable and Callable — interfaces for defining tasks, with Callable allowing returning results and throwing exceptions.
- ExecutorService — an interface for managing thread pools and executing tasks asynchronously.
- Future and CompletableFuture — for obtaining the result of an asynchronous operation and building processing chains.
Example of using CompletableFuture:
import java.util.concurrent.CompletableFuture;
public class AsyncExample {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
}).thenAccept(result -> {
System.out.println("Received: " + result);
});
System.out.println("Main thread continues to work");
}
}