Java - Concurrency — Threads & Executors

Concurrency — Threads & Executors

Threads and Runnables

Thread t = new Thread(() -> System.out.println("Hi"));
t.start();
t.join();

Executors and Futures

var exec = java.util.concurrent.Executors.newFixedThreadPool(2);
var f = exec.submit(() -> 40 + 2);
try { System.out.println(f.get()); } finally { exec.shutdown(); }

Synchronization Basics

class Counter { private int n; synchronized void inc(){ n++; } synchronized int get(){ return n; } }
Architect note: Prefer higher-level constructs (ExecutorService, CompletableFuture) over raw threads in production code.

Try it

  1. Submit two tasks to a fixed thread pool and print their results with Future.get().
  2. Make a thread-safe counter using synchronized or AtomicInteger and increment it from multiple threads.