1
Multithreading in Java
Java
A thread is a lightweight unit of execution inside a process. Create one by extending Thread or implementing Runnable (preferred).
New → Runnable → Running → Terminated
class Counter {
private int count = 0;
public synchronized void increment() { count++; } // one thread at a time
public int get() { return count; }
}
Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join(); // wait for both
System.out.println(c.get()); // 2000
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("from the pool"));
pool.shutdown();
start() creates a new thread and calls run(); calling run() directly just runs it on the current thread.