1Z0-809 practice question 3 of 25

Given: class Worker extends Thread { CyclicBarrier cb; public Worker(CyclicBarrier cb) { this.cb = cb; } public void run () { try { cb.await()…

Full set: 196 questions
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
A: At line n2, insert CyclicBarrier cb = new CyclicBarrier(2, master);
B: Replace line n1 with class Master extends Thread {
C: At line n2, insert CyclicBarrier cb = new CyclicBarrier(1, master); Correct answer
D: At line n2, insert CyclicBarrier cb = new CyclicBarrier(master);
Correct Answer:
C. At line n2, insert CyclicBarrier cb = new CyclicBarrier(1, master);
Explanation

The goal is to execute the run methods of both Worker and Master. A CyclicBarrier can be configured with a barrierAction (a Runnable) that executes when the barrier is tripped. By setting the number of parties to 1 (new CyclicBarrier(1, master)), the barrier will trip as soon as the single Worker thread calls cb.await(). This immediately triggers the master Runnable to execute its run method. After the barrier action completes, the Worker thread is unblocked and proceeds to execute the rest of its run method, printing "Worker...".

Why Incorrect

A. A CyclicBarrier with 2 parties will cause the Worker thread to wait indefinitely because only one thread (worker) calls await(), and the barrier is never tripped.
B. Changing Master to extend Thread does not cause its run method to be executed, as no Master thread is ever started with .start().
D. The CyclicBarrier class does not have a constructor that accepts only a Runnable argument. This line would result in a compilation error.

References

1. Oracle, "Java SE 8 API Specification, java.util.concurrent.CyclicBarrier," docs.oracle.com. The constructor CyclicBarrier(int parties, Runnable barrierAction) is documented, which creates a new CyclicBarrier that will trip when the given number of parties (parties) are waiting upon it, and which will execute the given barrier action when the barrier is tripped.

2. Goetz, B., et al. (2006). Java Concurrency in Practice. Addison-Wesley Professional. Chapter 5.4, "Barriers," explains the mechanics of CyclicBarrier, including the barrier action.

Scroll to Top