☕ Java

Voici la traduction de l'article du russe vers le français, en respectant toutes les règles spécifiées :

Here is the translated HTML article in English, following all your rules. ```html

What is it and why? (a real-life analogy)

Imagine you are a head chef in a huge kitchen. You need to prepare a complex dinner: soup, a main course, and dessert. You have only one stove and one oven. If you do everything sequentially (soup first, then the main course, then dessert), dinner will be ready in 3 hours. The guests will get hungry and leave.

But what if you have assistants? One chops vegetables, the second watches the oven, the third whips the cream. While one assistant waits for the water to boil, another is already cutting the meat. As a result, dinner is ready in 1 hour. This is multithreading — the simultaneous execution of several tasks.

Now imagine a different situation. You are alone, but you have a smart timer. You put the soup on the stove, set the timer for 15 minutes, and go cut the salad. When the timer rings, you return to the soup. You don't stand by the stove; you do other things. This is asynchrony — you don't block yourself by waiting, but switch between tasks.

Key difference: Multithreading is when several chefs (threads) work simultaneously. Asynchrony is when one chef (thread) intelligently switches between tasks without idling while waiting.

In programming, we often encounter tasks that require waiting: reading a file, a request to a server, processing a large data array. If the program just waits, the user will see a "frozen" screen. Multithreading and asynchrony solve this problem.

Theory: how it works from the inside

Processes and Threads

Imagine your computer is a large office. A process is an individual employee with their own desk, computer, and documents. Each process works in its own isolated room (memory). A thread is a task that the employee performs. One employee can do several things: print a document, answer a phone call, and drink coffee. But physically, they do only one thing at any given moment, just switching quickly.

In Java, a program starts as one process. Inside this process, there can be many threads. The main thread is called main — it's like the director who starts all the other tasks.

How multithreading works in Java

Java uses the operating system's native threads. When you create a thread in Java, the operating system allocates it separate time on the processor. If you have a 4-core processor, then 4 threads can work truly simultaneously. The rest will wait their turn, but the switching happens so fast (milliseconds) that it seems like everything is working at the same time.

A problem arises when multiple threads try to modify the same data. Imagine two chefs simultaneously trying to add salt to the same dish. Someone will oversalt. In Java, this is called a race condition. To solve this problem, synchronizers are used — like a lock on the kitchen door: while one chef is salting, the second waits.

How asynchrony works in Java

Asynchrony in Java is implemented through CompletableFuture and ExecutorService. This is not magic — it's just smart thread management. You say: "Do this task when you have time, and let me know the result." While the task is running in the background, your main thread can do other things.

Imagine you ordered a pizza. You don't stand by the door waiting for the courier — you watch a movie. When the pizza arrives, the courier rings the doorbell (this is a callback). You pause the movie, pick up the pizza, and continue watching. This is asynchrony.

Syntax in Java: all forms and options

Creating threads: 3 ways

Method When to use Example
Inheriting from Thread Simple task, no need to inherit another class class MyThread extends Thread
Implementing Runnable Need to inherit another class, task without a result class MyTask implements Runnable
Implementing Callable Need to get a result or throw an exception class MyTask implements Callable<Integer>

Synchronization: key tools

Tool What it does Analogy
synchronized Locks access to a method or block of code for one thread Locked restroom: one goes in, others wait
volatile Ensures all threads see the current value of a variable Bulletin board: everyone sees the same thing
ReentrantLock More flexible locking than synchronized Lock with a key: you can try to lock and not wait
Semaphore Limits the number of threads that can work simultaneously Parking lot: only 5 cars can enter
CountDownLatch Waits until several threads finish their work Race start: waiting for all drivers to get in their cars

Asynchrony: CompletableFuture

Method What it does Example
supplyAsync() Starts a task asynchronously and returns a result CompletableFuture.supplyAsync(() -> 42)
thenApply() Transforms the result when it is ready future.thenApply(x -> x * 2)
thenAccept() Consumes the result when it is ready, without returning anything future.thenAccept(x -> System.out.println(x))
```