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
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)- A13% (6)
- B4% (2)
- C76% (34)
- D7% (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 callawait()before the barrier trips, but only oneWorkeris started - it blocks forever and neither print statement executes. - B (changing
Mastertoextends Thread) is irrelevant;masteris never.start()ed anywhere in the code fragment, so itsrun()still never executes. - D (
new CyclicBarrier(master)) is a compilation error - there is noCyclicBarrierconstructor that accepts only aRunnable; valid constructors require anint partiesargument.
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.