Given the code fragment:
What is the result ?
Given the code fragment:
What is the result ?
The given code uses a CyclicBarrier with a barrier threshold of 2. This means that the barrier is tripped and the barrier action is executed when two threads reach the barrier.await() call. Each thread sleeps for an increasing amount of time (1000ms, 2000ms, 3000ms, 4000ms) before adding to the list and waiting at the barrier. As there are four threads, this process will happen in two cycles: the first two threads reach the barrier, print the list containing two 'X's, and then the second two threads print the list containing four 'X's. Therefore, the result will be [X, X] [X, X, X, X].
Answer D, tested
Answer is D [X, X] [X, X, X, X]
D,tested
If we write that: final CyclicBarrier barrier = new CyclicBarrier(1, new Runnable() answer is A.
Answer is A, tested public static void main(String[] args) { final List<String> list = new CopyOnWriteArrayList<>(); final AtomicInteger ai = new AtomicInteger(0); final CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() { @Override public void run() { System.out.println(list); } }); Runnable r = new Runnable() { @Override public void run() { try { Thread.sleep(1000 * ai.incrementAndGet()); list.add("X"); barrier.await(); }catch (Exception e){ } } }; new Thread(r).start(); new Thread(r).start(); new Thread(r).start(); new Thread(r).start(); } output : [X, X] [X, X, X, X] //CyclicBarrier works for all every 2 threads reached to the barrier
Based on your output, answer should be D.
Answer is D. CyclicBarrier is reached 2 times and first time list contains 2 Xs and second time it contains 4 Xs.
Answer D - tested