Java SE 8 Programmer II — Question 147

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();
You have been asked to ensure that the run methods of both the Worker and Master classes are executed.
Which modification meets the requirement?

Answer options

Correct answer: C

Explanation

The correct answer is C because it creates a CyclicBarrier that allows one thread (the Worker) to wait for the Master to execute its run method before proceeding. Option A is incorrect as it specifies 2 parties, which is unnecessary and does not guarantee the Master runs. Option B does not include the Master, so it won't trigger its execution. Option D is invalid because the CyclicBarrier constructor does not accept a single object as an argument.