Chapter 10: Threads
Multiple Choice · Basic Concepts
Question 1: What Is Shared?
Which statement is true for two threads in the same Java program?
A: Threads share the address space of the process, i.e. the heap and class fields; so they can access the same object and a race condition can occur. Each thread has its own stack (local variables, call frames) and PC register. A separate address space is specific to processes.
Output Question · The Thread Class
Question 2: Name, Priority, Daemon
The program runs in main and has not created any other thread before. What does it print?
Thread a = new Thread(() -> { }, "worker"); Thread b = new Thread(() -> { }); Thread c = new Thread(() -> { }); c.setPriority(Thread.MAX_PRIORITY); System.out.println(a.getName() + " " + b.getName() + " " + c.getName()); System.out.println(b.getPriority() + " " + c.getPriority() + " " + b.isDaemon()); System.out.println(Thread.currentThread().getName());
Show answer
worker Thread-0 Thread-1 5 10 false main
- A thread given a name does not take an automatic number; the first two unnamed ones become
Thread-0andThread-1. - Priority is inherited from the creating thread (main, 5 =
NORM_PRIORITY);MAX_PRIORITYis 10. The daemon property is inherited from the creator too: main is not a daemon. currentThread()is the thread running this line: main. a, b and c were never started.
Output Question · Life Cycle
Question 3: Four States and a Second start
sleepMs(ms) is a helper that wraps Thread.sleep in try-catch. What does the program print?
Thread t = new Thread(() -> sleepMs(300)); System.out.println(t.getState()); t.start(); Thread.sleep(100); System.out.println(t.getState()); t.join(); System.out.println(t.getState() + " " + t.isAlive()); try { t.start(); } catch (IllegalThreadStateException e) { System.out.println("cannot be restarted"); }
Show answer
NEW TIMED_WAITING TERMINATED false cannot be restarted
- Created but not started:
NEW. - After 100 ms, t is inside its 300 ms
sleep:TIMED_WAITING(timed waiting). join()waits until t finishes:TERMINATED,isAlive()is false.- A finished thread cannot be restarted:
IllegalThreadStateException.
Step-by-Step Trace · Creating and Starting
Question 4: run() First, Then start()
The same Thread object is run first with run(), then with start(). Which thread prints what? The stack panel shows the call stack of the currently running thread.
The Thread object is created; its name is T and its state is NEW. There is no separate stack yet.
t.run() is an ordinary method call: a new frame is added to main's stack; currentThread() is main.
The thread never started: still NEW.
start(): the JVM creates a new stack for T and starts run() there; start() returns immediately.
main waits in join() (WAITING). T runs on its own stack; currentThread() is now T.
T finished, join() returned. The output is the same on every run: the run() call is in main, after start() it is in T, and join() fixes the order.
Thread t = new Thread(() ->
System.out.println("run: "
+ Thread.currentThread().getName()), "T");
t.run();
System.out.println("A " + t.getState());
t.start();
t.join();
System.out.println("B " + t.getState());Multiple Choice · Creating and Starting
Question 5: A Class That Already Extends Another
class Clock extends JLabel — its object will run in a thread that updates its own text every second. Which approach compiles and works correctly?
B: Java allows inheritance from only one class; extends JLabel, Thread does not compile. Since there is no limit on the number of interfaces, implements Runnable is added and the object is passed to a Thread and started with start(). Calling run() directly does not open a new thread; the code runs in the caller's thread.
Multiple Choice · Creating and Starting
Question 6: Possible Outputs
These lines run in main. Which outputs can appear on screen?
Thread a = new Thread(() -> System.out.print("a")); Thread b = new Thread(() -> System.out.print("b")); a.start(); a.join(); b.start(); System.out.print("m"); b.join();
C: a.join() does not let main proceed until a has finished: a is always the first letter. After b is started, main's printing of m races with b running: abm or amb. b.join() only prevents the program from finishing before b. In 300 trials amb was always seen (main acted before the new thread); but abm is also a valid order, no order is guaranteed.
Output Question · Control and Stopping
Question 7: join(ms) and Reading the Result
result is a static int field (initially 0); sleepMs(ms) is the helper that wraps sleep. What does the program print?
Thread h = new Thread(() -> {
sleepMs(200);
result = 42;
});
h.start();
System.out.println("1: " + result);
h.join(50);
System.out.println("2: " + result + " "
+ h.isAlive());
h.join();
System.out.println("3: " + result + " "
+ h.isAlive());Show answer
1: 0 2: 0 true 3: 42 false
- h is still sleeping for 200 ms: the result has not been written, 0.
join(50)waits at most 50 ms and returns even if h has not finished: still 0, h is alive.join()waits indefinitely; the 42 that h wrote is visible to main as well once h finishes (join is a synchronization point).
Step-by-Step Trace · Synchronization
Question 8: The Lost Withdrawal
The balance is 500. T1 calls deposit(100), T2 calls withdraw(30); balance += m and balance -= m each consist of the steps read, compute, write. With the order of steps shown, what is the balance in the end? What should the correct result have been?
Correct result: 500 + 100 − 30 = 570. No synchronization.
T1 reads: 500.
Context switch: T2 reads too, and also sees 500.
T2 subtracts and writes: balance 470.
T1 continues with the stale value: it computes 500 + 100 = 600 ...
... and writes 600: T2's withdrawal is lost. With this order the result is 600; with the reverse order 470 could also have come out. Fix: make both methods synchronized (same monitor: this).
class Account {
private int balance = 500;
void deposit(int m) {
balance += m; // read, add, write
}
void withdraw(int m) {
balance -= m; // read, subtract, write
}
}Multiple Choice · Synchronization
Question 9: Which Lock?
class C has synchronized void p() and static synchronized void q(); x and y are two separate C objects. Which two calls cannot run at the same time in different threads?
A: An instance method locks the monitor of the this object, a static method locks the monitor of the C.class object. Two x.p() calls want the same monitor (x): one waits BLOCKED. x and y are different monitors; the lock of C.q() is also different from that of the instance methods, so the other pairs do not block each other.
Spot the Bug · Synchronization
Question 10: synchronized but Still a Race
Two threads run two separate objects of this class: new Thread(new Counter()).start(); twice, then two join(). run is synchronized, so why can the total come out smaller than 200000? Fix it.
class Counter implements Runnable { static int total = 0; public synchronized void run() { for (int i = 0; i < 100000; i++) { total++; } } }
Show answer
Each thread takes the monitor of its own object (this): two different locks do not block each other, but the protected data is the shared static toplam. Three runs gave 134276, 158236, 186709. Fix: everyone uses the same lock.
public void run() { for (int i = 0; i < 100000; i++) { synchronized (Counter.class) { total++; } } }
Or use AtomicInteger with incrementAndGet(). If the two threads shared the same object, the original code would also work correctly.
Multiple Choice · Visibility
Question 11: What Does volatile Give?
static volatile int count field is incremented by two threads, 100,000 times each, with count++. Which statement is true?
D: volatile guarantees that every read comes from main memory and every write is visible immediately; that is enough for a single read/write such as a flag. count++ is a read–add–write sequence; if two threads interleave, an increment is lost. In the experiment in the slides, 163299, 164441, 199332 were found. Fix: AtomicInteger or synchronized.
Multiple Choice · Explicit Locks
Question 12: The Reentrant Lock
What does the program print?
ReentrantLock k = new ReentrantLock();
k.lock();
k.lock();
System.out.print(k.getHoldCount() + " ");
k.unlock();
System.out.print(k.isLocked() + " ");
k.unlock();
System.out.println(k.isLocked());D: ReentrantLock lets the thread holding the lock acquire the same lock again; only the hold count increases: 2. One unlock() reduces the count to 1; the lock still belongs to main (isLocked() is true). The second unlock() brings the count to 0 and the lock is released. Each lock() needs one unlock(); an extra unlock() would throw IllegalMonitorStateException.
Spot the Bug · Explicit Locks
Question 13: unlock Without finally
t1 calls divide(10, 0), then (after t1 has finished) t2 calls divide(10, 2). What is seen on screen, and in what state does t2 remain? Fix the bug.
static final Lock lock = new ReentrantLock(); static void divide(int a, int b) { lock.lock(); System.out.println(a / b); lock.unlock(); }
Show answer
In t1, 10 / 0 throws ArithmeticException; unlock() is never reached, so the lock stays locked. Only t1's stack trace appears; 5 is never printed. t2 waits forever in lock(), in state WAITING (not BLOCKED: that is for monitor locks).
static void divide(int a, int b) { lock.lock(); try { System.out.println(a / b); } finally { lock.unlock(); // runs on an exception too } }
A synchronized block has no such problem: the monitor is released even when an exception leaves it.
Multiple Choice · Condition Synchronization
Question 14: wait() and sleep()
Inside a synchronized block, which statement describes the difference between kilit.wait() and Thread.sleep(1000)?
B: Holding the lock while waiting for a condition would stop the thread that will change the condition from entering; that is why wait() releases the lock and, when woken by notify/notifyAll, reacquires the lock and continues. sleep() does not care about locks. wait(ms) variant also exists; wait() called outside synchronized throws IllegalMonitorStateException.
Coding Question · Condition Synchronization
Question 15: Summing with ArrayBlockingQueue
With a capacity-2 ArrayBlockingQueue: the producer thread puts 1–5 and then the end marker −1; main takes and adds until −1 arrives. Write the code; what is the output?
Show answer
BlockingQueue<Integer> q = new ArrayBlockingQueue<>(2); Thread producer = new Thread(() -> { try { for (int i = 1; i <= 5; i++) q.put(i); // waits if full q.put(-1); // end marker } catch (InterruptedException e) { } }); producer.start(); int total = 0; while (true) { int v = q.take(); // waits if empty if (v < 0) break; total += v; } producer.join(); System.out.println("Total: " + total);
The output is always Total: 15. put and take do the waiting and waking themselves. Because the queue is FIFO, −1 comes last.
Multiple Choice · Synchronizers
Question 16: The Right Tool
In a game, 4 player threads will wait for each other at the end of every round; when all four have arrived, the round scores will be computed once and all will move on to the next round together. This repeats every round. Which tool is suitable?
C: CyclicBarrier holds everyone in await() until the party is full; when full, it runs the barrier action once and releases everyone. Because it is reusable, the same barrier is used for every round. CountDownLatch is single-use, its counter is not reset; Semaphore limits concurrent entry; Exchanger swaps only between two threads.
Step-by-Step Trace · Synchronizers
Question 17: Semaphore and CountDownLatch
What does this code, running in a single thread, print? Follow the permits and counters at each step.
Semaphore with 2 permits.
acquire(): a permit was available, drops to 1.
tryAcquire(): a permit is available, takes it and returns true.
No permit: tryAcquire returns false without waiting (acquire would wait forever).
Three releases: a Semaphore does not track who owns permits and does not treat the initial count as an upper limit; permits go up to 3.
Printed.
The latch counts down from 2: two countDown calls give 0.
When the count is 0, countDown has no effect; it does not go negative and is not reset.
The latch is open: await returns true without waiting (it would return false if the timeout had expired).
Semaphore s = new Semaphore(2); s.acquire(); boolean x1 = s.tryAcquire(); boolean x2 = s.tryAcquire(); s.release(); s.release(); s.release(); System.out.println(x1 + " " + x2 + " " + s.availablePermits()); CountDownLatch m = new CountDownLatch(2); m.countDown(); m.countDown(); m.countDown(); System.out.println(m.getCount() + " " + m.await(10, TimeUnit.MILLISECONDS));
Output Question · Other Tools
Question 18: The Interrupt Flag
What does the program print?
Thread t = new Thread(() -> { try { Thread.sleep(5000); System.out.println("woke up"); } catch (InterruptedException e) { System.out.println("interrupted " + Thread .currentThread().isInterrupted()); } }); t.start(); Thread.sleep(100); t.interrupt(); t.join(); Thread.currentThread().interrupt(); System.out.println(Thread.interrupted() + " " + Thread.interrupted());
Show answer
interrupted false true false
- t is in its 5-second
sleepwheninterrupt()arrives:sleepthrowsInterruptedExceptionand, while doing so, clears the interrupt flag; that is why, inside the catch,isInterrupted()is false. “woke up” is not printed. Code that wants to report the interruption upward re-sets the flag inside the catch withThread.currentThread().interrupt(). - main sets its own flag. static
Thread.interrupted()reads and clears the flag: the first call is true, the second false.
Multiple Choice · Other Tools
Question 19: ThreadLocal Copies
What does the program print?
ThreadLocal<Integer> t =
ThreadLocal.withInitial(() -> 0);
t.set(5);
Thread x = new Thread(() -> {
t.set(t.get() + 1);
System.out.println("x: " + t.get());
});
x.start();
x.join();
System.out.println("main: " + t.get());A: Each thread sees its own copy of the ThreadLocal. main's 5 does not pass to x; at its first get(), x starts from the 0 in withInitial and makes it 1. What x writes does not affect main's copy either: main sees 5. Unshared data does not race.