In the StartVsRun program of Section 3, the Worker is named worker-1 and its run() prints the current thread's name. main calls w.run(), then w.start(), then w.join(), then prints 'main done'. What is printed, and what would a second w.start() do?
Multithreading lets one Java program do several things at once. Covers process vs thread, creating threads (Thread vs Runnable), start() vs run(), the six thread states, priorities, sleep/join/yield/interrupt, daemon threads, synchronization, wait/notify, deadlock, volatile and java.util.concurrent.
Thread or implementing Runnable — Runnable is preferred: the class can still extend another class, and the task stays separate from the thread.start() creates a new thread that then calls run(); calling run() directly runs it in the current thread. Starting a thread twice → IllegalThreadStateException.Thread.State: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. Textbook five-state model: newborn, runnable, running, blocked, dead.setDaemon(true) must come before start(); daemons do not keep the JVM alive.synchronized methods and blocks take the object's intrinsic lock (monitor); static synchronized locks the Class object. volatile gives visibility, not atomicity.wait(), notify(), notifyAll() are Object methods, legal only while holding that object's monitor (else IllegalMonitorStateException). wait() releases the lock; sleep() keeps it.Multitasking comes in two forms. Process-based multitasking runs several programs at once — a browser, a music player and an editor. Thread-based multitasking runs several tasks inside one program — a word processor that checks spelling and auto-saves while you type. Java supports thread-based multitasking directly in the language and its libraries.
| Point | Process | Thread |
|---|---|---|
| What it is | A program in execution | A single path of execution inside a process |
| Memory | Its own address space (code, data, heap) | Shares the process's code, data and heap; owns its stack, program counter and registers |
| Cost to create and switch | Heavyweight | Lightweight |
| Communication | Inter-process communication: pipes, sockets, shared memory | Directly through shared objects — which then need synchronization |
| Failure | A crash usually stays inside that process | A misbehaving thread can corrupt data used by all threads |
| In Java | Each java command starts a separate JVM process | The main thread, GC threads and every Thread you start |
When a program starts, the JVM creates the main thread to run main(). It is named "main" and has priority 5. Any code can obtain the thread that is executing it with the static method Thread.currentThread().
public class MainThread {
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println(t.getName() + " " + t.getPriority() + " " + t.isDaemon()); // main 5 false
t.setName("boss");
System.out.println(t); // Thread[boss,5,main] (Java 19+ adds the id: Thread[#1,boss,5,main])
}
}There are two classic ways to define what a thread does. Extend Thread and override its run() method, or implement Runnable — an interface with the single method void run() — and hand the object to a Thread's constructor. Either way, calling start() launches the thread. Since Java 8, Runnable is a functional interface, so a lambda can serve as the task.
class Counter extends Thread { // way 1: extend Thread
public void run() {
for (int i = 1; i <= 3; i++)
System.out.println(getName() + ": " + i);
}
}
class Printer implements Runnable { // way 2: implement Runnable
private final String msg;
Printer(String msg) { this.msg = msg; }
public void run() {
for (int i = 1; i <= 3; i++)
System.out.println(Thread.currentThread().getName() + ": " + msg + " " + i);
}
}
public class Create {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread p = new Thread(new Printer("hello"), "printer"); // task + thread name
Thread l = new Thread(() -> System.out.println("lambda thread")); // way 3: a lambda
c.start(); p.start(); l.start(); // three new threads now run concurrently
c.join(); p.join(); l.join(); // main waits for all three to finish
System.out.println("all done");
}
}| Constructor | Use |
|---|---|
| Thread() | For a subclass that overrides run(); gets an automatic name such as Thread-0 |
| Thread(String name) | A subclass with a chosen name |
| Thread(Runnable target) | Run target's run() in a new thread |
| Thread(Runnable target, String name) | The same, with a name |
| Thread(ThreadGroup group, Runnable target, String name) | Also places the thread in a ThreadGroup |
A task that must return a value or throw a checked exception implements Callable<V> (Java 5) instead: its method is V call() throws Exception. Callables are submitted to an ExecutorService, which returns a Future<V> whose get() waits for the result (Section 8).
start() asks the JVM to create a new thread of execution with its own call stack; that new thread then calls run(), while start() itself returns immediately. run() is an ordinary method: calling it directly simply executes its body in the current thread — no new thread, no concurrency. A Thread object can be started only once; a second start() throws IllegalThreadStateException, even after the thread has finished.
class Worker extends Thread {
public void run() {
System.out.println("run() in " + Thread.currentThread().getName());
}
}
public class StartVsRun {
public static void main(String[] args) throws InterruptedException {
Worker w = new Worker();
w.setName("worker-1");
w.run(); // a plain method call: executes in the main thread
w.start(); // a new thread named worker-1 executes run()
w.join(); // wait for it, so the output order is fixed
System.out.println("main done");
// w.start(); // would throw IllegalThreadStateException
}
}Since Java 5 every thread reports one of six states through getState(), defined by the enum Thread.State. A thread is in exactly one state at any moment.
| State | Meaning | How a thread gets there |
|---|---|---|
| NEW | Created but not yet started | new Thread(…) |
| RUNNABLE | Ready to run or actually running — Java does not separate the two | start(); returning from sleep or wait; obtaining a lock; also while blocked in native I/O |
| BLOCKED | Waiting to acquire a monitor lock | Entering a synchronized method/block whose lock another thread holds, or re-entering after wait() |
| WAITING | Waiting indefinitely for another thread | wait(), join() or LockSupport.park() without a time-out |
| TIMED_WAITING | Waiting with a time limit | sleep(ms), wait(ms), join(ms) |
| TERMINATED | Finished | run() returned, or ended with an uncaught exception |
| Transition | Trigger |
|---|---|
| NEW → RUNNABLE | start() |
| RUNNABLE → TIMED_WAITING | sleep(ms), wait(ms), join(ms) |
| RUNNABLE → WAITING | wait(), join() |
| RUNNABLE → BLOCKED | Trying to enter a synchronized region whose lock is taken |
| WAITING / TIMED_WAITING → BLOCKED → RUNNABLE | notify()/notifyAll() or time-out, then the monitor must be re-acquired |
| WAITING / TIMED_WAITING → RUNNABLE | The joined thread ends, the sleep ends, or interrupt() |
| BLOCKED → RUNNABLE | The lock becomes free and this thread obtains it |
| RUNNABLE → TERMINATED | run() completes or throws |
Textbooks such as Balagurusamy use a five-state model: newborn (= NEW), runnable and running (together = RUNNABLE), blocked (= BLOCKED, WAITING and TIMED_WAITING) and dead (= TERMINATED). The old methods stop(), suspend() and resume() were deprecated in Java 1.2 because they are unsafe — stop() releases locks mid-update, suspend() can freeze a thread while it holds a lock — and modern JDKs no longer support them. Use interrupts or a volatile flag instead.
public class States {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try { Thread.sleep(500); } catch (InterruptedException e) { }
});
System.out.println(t.getState()); // NEW
t.start();
Thread.sleep(100); // give t time to begin its 500 ms sleep
System.out.println(t.getState()); // TIMED_WAITING
t.join(); // wait until t finishes
System.out.println(t.getState()); // TERMINATED
}
}| Method | Static? | Effect |
|---|---|---|
| sleep(ms) | Yes | Pause the current thread for at least ms milliseconds (TIMED_WAITING); keeps any locks it holds; throws InterruptedException |
| join() / join(ms) | No | Wait until that thread terminates (or the time-out passes) |
| yield() | Yes | Hint that the current thread is willing to give up the CPU; the scheduler may ignore it |
| interrupt() | No | Set the thread's interrupt flag; a thread in sleep, wait or join wakes with InterruptedException |
| isInterrupted() / Thread.interrupted() | No / Yes | Test the flag; the static interrupted() also clears it |
| isAlive() | No | true from start() until the thread terminates |
| setPriority(p) / getPriority() | No | 1 = MIN_PRIORITY, 5 = NORM_PRIORITY (default), 10 = MAX_PRIORITY |
| setDaemon(true) / isDaemon() | No | Make it a background (daemon) thread — only before start() |
| currentThread() | Yes | The Thread object of the running thread |
| getName / setName / threadId() | No | Names and ids (threadId() since Java 19; getId() before) |
Priorities range from 1 to 10; a value outside that range throws IllegalArgumentException, and a new thread inherits the priority of the thread that created it. The JVM maps them onto the operating system's scheduler, so their effect varies by platform — they are hints, never a way to guarantee order or correctness.
A daemon thread is a background service thread (the garbage collector is one). The JVM exits as soon as only daemon threads remain, abandoning them mid-work — their finally blocks may never run. Call setDaemon(true) before start() (afterwards it throws IllegalThreadStateException); a thread created by a daemon is itself a daemon.
public class Interrupt {
public static void main(String[] args) throws InterruptedException {
Thread sleeper = new Thread(() -> {
try {
System.out.println("sleeping for 10 s");
Thread.sleep(10_000);
System.out.println("woke normally"); // not printed
} catch (InterruptedException e) {
System.out.println("interrupted! flag now " + Thread.currentThread().isInterrupted());
}
});
sleeper.start();
Thread.sleep(500); // let it fall asleep
sleeper.interrupt(); // wake it early
sleeper.join();
System.out.println("alive? " + sleeper.isAlive());
}
}
/* Output:
sleeping for 10 s
interrupted! flag now false (throwing InterruptedException clears the flag)
alive? false */When threads share data, the result can depend on the exact interleaving of their steps — a race condition. count++ looks like one operation but is three: read count, add 1, write it back. If two threads both read 5 before either writes, both write 6 and one increment is lost. Code that touches shared data and must not be interleaved is a critical section. (The Race-condition stepper in Module 2's operating-systems tools animates exactly this.)
class Counter {
private int count = 0;
void unsafeIncrement() { count++; } // read, add, write: not atomic
synchronized void safeIncrement() { count++; } // holds the lock on 'this' meanwhile
int get() { return count; }
}
public class Race {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 100_000; i++) c.safeIncrement(); };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.get()); // always 200000; with unsafeIncrement usually less
}
}Every Java object has an intrinsic lock, also called its monitor. A synchronized instance method acquires the lock of this on entry and releases it on exit — even if an exception is thrown; a static synchronized method locks the Class object (Counter.class); a synchronized block synchronized (obj) { … } locks any chosen object for just the critical section. Only one thread can own a given monitor at a time; others trying to enter wait in the BLOCKED state. Monitors are reentrant: a thread that holds a lock may enter other code synchronized on the same object.
class Account {
private double balance;
private final Object lock = new Object(); // outsiders cannot lock this object
void deposit(double amt) {
validate(amt); // no lock needed for this part
synchronized (lock) { // only the shared update is locked
balance += amt;
}
}
private void validate(double amt) {
if (amt <= 0) throw new IllegalArgumentException("amount must be positive");
}
}volatile solves a different problem: visibility. Without it, a thread may keep a field's value in a register or CPU cache and never notice another thread's update. A volatile field is always read from and written to main memory, and accesses to it are not reordered. It does not make compound actions atomic — count++ on a volatile int is still a race. Use it for flags; use synchronized or AtomicInteger.incrementAndGet() for counters.
class Poller implements Runnable {
private volatile boolean running = true; // without volatile the loop might never stop
public void run() {
while (running) {
// poll a sensor ...
}
}
void stop() { running = false; } // called from another thread
}Threads often need to wait for a condition — 'the buffer is not empty', 'the job is done'. Checking it in a loop (busy waiting) wastes CPU. Java's built-in mechanism lets a thread wait on an object until another thread notifies it.
wait(), notify() and notifyAll() are final methods of java.lang.Object — because any object can be a monitor — not of Thread.wait() releases the monitor and suspends the thread (WAITING; TIMED_WAITING for wait(ms)). It throws InterruptedException if interrupted.notify() wakes one arbitrary waiting thread; notifyAll() wakes all of them. A woken thread must re-acquire the monitor (it is BLOCKED meanwhile) before wait() returns.class Slot { // a one-item buffer shared by two threads
private int value;
private boolean full = false;
synchronized void put(int v) throws InterruptedException {
while (full) wait(); // occupied: release the lock and wait
value = v;
full = true;
System.out.println("produced " + v);
notifyAll(); // wake the consumer
}
synchronized int take() throws InterruptedException {
while (!full) wait(); // nothing to take yet
full = false;
System.out.println("consumed " + value);
notifyAll(); // wake the producer
return value;
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Slot slot = new Slot();
Thread producer = new Thread(() -> {
try { for (int i = 1; i <= 3; i++) slot.put(i); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
try { for (int i = 1; i <= 3; i++) slot.take(); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start();
consumer.start();
}
}
/* Output, always in this order:
produced 1 / consumed 1 / produced 2 / consumed 2 / produced 3 / consumed 3 */A deadlock occurs when two or more threads each hold a lock and wait for a lock held by another, so none can ever proceed. All four Coffman conditions hold at once: mutual exclusion, hold and wait, no preemption and circular wait. The simplest prevention is to make every thread acquire locks in the same global order, which breaks the circular wait.
public class Deadlock {
static final Object fileLock = new Object();
static final Object printerLock = new Object();
public static void main(String[] args) {
Thread a = new Thread(() -> {
synchronized (fileLock) {
System.out.println("A holds file, wants printer");
pause();
synchronized (printerLock) { System.out.println("A printed"); }
}
});
Thread b = new Thread(() -> {
synchronized (printerLock) { // the opposite order: the bug
System.out.println("B holds printer, wants file");
pause();
synchronized (fileLock) { System.out.println("B saved"); }
}
});
a.start();
b.start();
}
static void pause() {
try { Thread.sleep(100); } catch (InterruptedException e) { }
}
}A ThreadGroup collects threads so they can be handled together — activeCount(), interrupt() on the whole group, setMaxPriority(). Every thread belongs to one (the main thread to the group named "main"), and new Thread(group, task, name) places a thread explicitly. ThreadGroup is largely legacy today; thread pools manage groups of threads instead.
| Tool | Purpose |
|---|---|
| ExecutorService — Executors.newFixedThreadPool(n) | A pool of reusable threads: submit() tasks, shutdown() when finished |
| Callable and Future | Tasks that return values; future.get() waits for the result |
| ReentrantLock | An explicit lock: lock() … unlock() in finally; tryLock(time) avoids deadlock |
| ReadWriteLock | Many readers or one writer at a time |
| Semaphore | Allows at most N threads into a section at once |
| CountDownLatch, CyclicBarrier | Wait until N events have happened / N threads have arrived |
| BlockingQueue (ArrayBlockingQueue) | put() blocks when full and take() blocks when empty — producer–consumer without wait/notify |
| AtomicInteger, AtomicLong | Lock-free atomic operations such as incrementAndGet() |
| ConcurrentHashMap | A thread-safe map with fine-grained locking |
import java.util.concurrent.*;
public class Pool {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2); // two worker threads
Future<Integer> f = pool.submit(() -> { // a Callable<Integer>
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
return sum;
});
System.out.println("sum = " + f.get()); // waits for the result
pool.shutdown(); // accept no new tasks
}
}Thread.ofVirtual().start(task), Executors.newVirtualThreadPerTaskExecutor()): very cheap threads managed by the JVM, so a server can afford one thread per request even with millions of requests.Try the problem first, then reveal the working one step at a time.
In the StartVsRun program of Section 3, the Worker is named worker-1 and its run() prints the current thread's name. main calls w.run(), then w.start(), then w.join(), then prints 'main done'. What is printed, and what would a second w.start() do?
Two threads run count++ (count is a shared int, currently 5) without synchronization. Show an interleaving that loses an update, and explain why the synchronized version of the Race program always prints 200000.
Using the Slot class of Section 7, explain why the output must be produced 1, consumed 1, produced 2, consumed 2, produced 3, consumed 3, whichever thread happens to run first.
For the States program of Section 4 (t sleeps 500 ms; main prints t.getState() before start, 100 ms after start, and after join), give each printed state and justify it.
What happens here? Thread t = new Thread(() -> System.out.println("hi")); t.start(); t.start();
main starts a thread whose run() loops forever printing "tick" every second, then main sleeps 3 seconds and returns. How long does the program run (a) if the thread is a daemon, (b) if it is not?
This compiles, but what happens when it runs? Object o = new Object(); o.wait(); (inside a method that declares throws InterruptedException).
Give the Thread.State of a thread that is: (a) trying to enter a synchronized method another thread is executing; (b) inside sleep(1000); (c) inside join() with no time-out; (d) finished; (e) created but not started; (f) blocked reading from a network socket.
Fix the Deadlock program of Section 8 so that it can never deadlock, and explain why the fix works.
run() directly does not start a new thread — the body runs in the caller's thread. Only start() creates a thread.wait(), notify() and notifyAll() belong to Object; sleep(), yield(), join() and start() belong to Thread (sleep and yield are static).sleep() keeps every lock the thread holds; wait() releases the monitor of the object it is called on (only that one).yield() are only hints, so the order of output from unsynchronized threads is never guaranteed — 'cannot be predicted' is often the right answer.volatile is not atomic; two synchronized methods on different objects do not exclude each other; a static synchronized method locks the Class object, not an instance.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.