CKTIS / Java
Thread.start() : démarrer un thread
`Thread.start()` programme l’exécution dans un thread distinct. Appeler `run()` directement ne démarre aucun thread ; `join()` permet d’attendre sa fin.
Version : Java SE 21
Syntaxe
public void start()
// Call on a java.lang.Thread instance:
thread.start();Thread.start() est une méthode d’instance de java.lang.Thread sans argument ni valeur de retour (void). En Java SE 21, elle programme l’exécution du thread concerné, qu’il soit de plateforme ou virtuel, indépendamment du thread appelant. Elle n’attend pas sa fin et ne garantit pas que son code sera exécuté avant l’instruction suivante de l’appelant. Un objet Thread ne peut être démarré qu’une fois. Un deuxième appel à start() lève IllegalThreadStateException, même si le thread est déjà terminé.
new Thread(task) crée un thread de plateforme sans le démarrer. Appeler run() directement sur cet objet exécute la tâche de manière synchrone dans le thread appelant : aucun nouveau thread ne démarre. Appeler run() directement sur un thread virtuel ne fait rien. Utilisez start() pour exécuter la tâche dans un thread distinct.
Appelez join() après start() si la suite du code doit attendre la fin du thread. join() peut lever InterruptedException si le thread en attente est interrompu. Les règles happens-before rendent les écritures de l’appelant avant start() visibles au thread démarré, et les écritures de ce dernier visibles au thread en attente après le retour normal de join(). Cela ne rend pas sûres toutes les modifications concurrentes de données partagées.
Exemples
public class ThreadStartDemo {
public static void main(String[] args) throws InterruptedException {
Thread caller = Thread.currentThread();
Runnable task = () -> System.out.println(
Thread.currentThread() == caller ? "caller thread" : "worker thread");
Thread worker = new Thread(task);
worker.run();
worker.start();
worker.join();
System.out.println("worker finished");
}
}Résultat
caller thread worker thread worker finished
La même tâche s’exécute d’abord dans le thread appelant (`caller thread`), puis dans le thread de travail (`worker thread`). Après `join()`, le programme affiche `worker finished`.
Leçons associées
- Java · Leçon 49 · Intermédiaire · Version : 2
- Java · Leçon 52 · Intermédiaire · Version : 2
- Java · Leçon 53 · Intermédiaire · Version : 2
- Java · Leçon 58 · Intermédiaire · Version : 2