Java SE 8 Programmer II — Question 14

Given:
class Worker extends Thread {
CyclicBarrier cb;
public Worker(CyclicBarrier cb) { this.cb = cb; }
public void run () {
try {
cb.await();
System.out.println("Worker…");
} catch (Exception ex) { }
}
}
class Master implements Runnable { //line n1
public void run () {
System.out.println("Master…");
}
}
and the code fragment:
Master master = new Master();
//line n2
Worker worker = new Worker(cb);
worker.start();
run methods of both the Worker and Master classes are executed.
You have been asked to ensure that the
Which modification meets the requirement?
line n2, insert CyclicBarrier cb = new CyclicBarrier(2, master);

Answer options

Correct answer: B

Explanation

The correct modification is option B because it creates a CyclicBarrier that allows one thread (the Worker) to wait for another (the Master) before proceeding. Option A is incorrect because extending Thread does not fulfill the requirement for synchronization with the CyclicBarrier. Options C and D do not properly use the CyclicBarrier constructor, failing to ensure that both threads can synchronize as intended.