nerdexam
Oracle

1Z0-809 · Question #51

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…

The correct answer is C. At line n2, insert CyclicBarrier cb = new CyclicBarrier(1, master). Option C works because CyclicBarrier(1, master) creates a barrier that trips as soon as 1 thread calls await(). When the single Worker thread calls cb.await(), the barrier immediately fires, executing master.run() (printing "Master..."), then releases the Worker to continue and…

Question

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?

Options

  • AAt line n2, insert CyclicBarrier cb = new CyclicBarrier(2, master);
  • BReplace line n1 with class Master extends Thread { }
  • CAt line n2, insert CyclicBarrier cb = new CyclicBarrier(1, master);
  • DAt line n2, insert CyclicBarrier cb = new CyclicBarrier(master);

How the community answered

(45 responses)
  • A
    13% (6)
  • B
    4% (2)
  • C
    76% (34)
  • D
    7% (3)

Explanation

Option C works because CyclicBarrier(1, master) creates a barrier that trips as soon as 1 thread calls await(). When the single Worker thread calls cb.await(), the barrier immediately fires, executing master.run() (printing "Master..."), then releases the Worker to continue and print "Worker...". Both run() methods execute exactly as required.

Why the distractors fail:

  • A (new CyclicBarrier(2, master)) requires 2 threads to call await() before the barrier trips, but only one Worker is started - it blocks forever and neither print statement executes.
  • B (changing Master to extends Thread) is irrelevant; master is never .start()ed anywhere in the code fragment, so its run() still never executes.
  • D (new CyclicBarrier(master)) is a compilation error - there is no CyclicBarrier constructor that accepts only a Runnable; valid constructors require an int parties argument.

Memory tip: Match the party count to the number of threads that actually call await(). Count the .start() calls in scope - here there is exactly one (worker.start()), so parties = 1. The Runnable second argument is a bonus action that fires at the barrier, giving you a clean way to run non-thread Runnables without extending Thread.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice