Junior — Middle
How to implement asynchronous task execution in Java?
sobes.tech AI
Answer from AI
In Java (including on Android), there are several approaches to perform asynchronous tasks:
-
Thread / Runnable: Create a new thread to execute a task.
-
ExecutorService: Managed thread pool for executing tasks.
-
AsyncTask (deprecated in Android): Allowed executing tasks in the background with UI updates.
-
CompletableFuture (Java 8+): Enables writing asynchronous code with chains of actions.
-
RxJava: A library for reactive programming with support for asynchrony.
-
Coroutines (Kotlin): A modern way of asynchronous programming on Android.
Example using ExecutorService:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
// Long operation
System.out.println("Executing in background");
// After execution, UI can be updated via Handler or runOnUiThread
});
executor.shutdown();
This method allows executing tasks in a separate thread without blocking the main application thread.