Junior
What is multithreading, parallelism, and asynchrony?
sobes.tech AI
Answer from AI
- Multithreading — the ability of a program to execute multiple threads of execution within a single process. Threads share common memory.
- Parallelism — simultaneous execution of multiple tasks (processes or threads) on multiple computing resources (CPU cores, machines).
- Asynchrony — a way of executing a task where the main thread does not block waiting for a side operation to complete. The task is launched, control returns immediately, and the result is processed later, upon completion of the operation (for example, using callbacks or Future/CompletableFuture).
| Concept | Simultaneity | Main thread blocking | Execution resources | Main goal |
|---|---|---|---|---|
| Multithreading | Can be or not | No (if working correctly) | One or multiple cores | Improving responsiveness, core utilization |
| Parallelism | Yes | No (for threads) | Multiple computing resources | Increasing performance |
| Asynchrony | Can be or not | No | Depends on implementation | Non-blocking I/O, responsiveness |
// Example of multithreading in Java
public class MultithreadingExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> { // Thread 1
System.out.println("Thread 1 started.");
// Performing some task
System.out.println("Thread 1 finished.");
});
Thread thread2 = new Thread(() -> { // Thread 2
System.out.println("Thread 2 started.");
// Performing another task
System.out.println("Thread 2 finished.");
});
thread1.start(); // Start thread 1
thread2.start(); // Start thread 2
}
}
// Example of asynchrony in Java using CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class AsynchronousExample {
public static CompletableFuture<String> fetchDataAsync() {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Asynchronous operation started...");
try {
Thread.sleep(2000); // Simulate a long operation
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Asynchronous operation completed.");
return "Data received";
});
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("Main thread: Starting to fetch data asynchronously.");
CompletableFuture<String> futureData = fetchDataAsync(); // Launch async task
System.out.println("Main thread: Continuing work without waiting for the result.");
// Handling the result when it becomes available
futureData.thenAccept(result -> {
System.out.println("Main thread: Asynchronous result received: " + result);
});
// Or, if you need to wait for the result (blocking call)
// String data = futureData.get();
// System.out.println("Main thread: Synchronously received result: " + data);
System.out.println("Main thread: Main work is done.");
// Important: the main thread must remain active for thenAccept to execute
Thread.sleep(3000); // Simulate waiting
}
}