📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 5

Retour
Créer un thread en héritant de Thread
Facile
class MonThread extends Thread {
    public void run() {
        System.out.println("Le thread est en cours d'exécution.");
    }
}
Créer un thread en implémentant Runnable
Facile
class MonRunnable implements Runnable {
    public void run() {
        System.out.println("Le runnable est en cours d'exécution.");
    }
}
Thread t = new Thread(new MonRunnable());
t.start();
Méthode synchronisée (synchronized)
Intermédiaire
class Table {
    synchronized void printTable(int n) {
       // ... code de la section critique
    }
}
Utiliser Future et Callable
Avancé
Callable<Integer> task = () -> {
    TimeUnit.SECONDS.sleep(1);
    return 123;
};
Future<Integer> future = executor.submit(task);
Integer result = future.get(); // Bloquant
Utiliser un ExecutorService
Avancé
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
    Runnable worker = new WorkerThread("" + i);
    executor.execute(worker);
}
executor.shutdown();