Java SE 8 Programmer II Exam: Question Answered

Which statement is true?

Question

Given the code fragments: class MyThread implements Runnable { private static AtomicInteger count = new AtomicInteger (0); public void run (){ int x = count.incrementAndGet(); System.out.print (x+" "); } } and Thread thread1 = new Thread(new MyThread()); Thread thread2 = new Thread(new MyThread()); Thread thread3 = new Thread(new MyThread()); Thread [] ta = {thread1, thread2, thread3}; for (int x= 0; x < 3; x++){ ta[x].start(); } Which statement is true?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The code defines a MyThread class that implements the Runnable interface and contains a static AtomicInteger variable named count. The run method of MyThread increments count using the incrementAndGet() method and prints the resulting value.

The code then creates three threads using the Thread class and passing in a new instance of MyThread as the target. The threads are stored in an array named ta.

Finally, the code starts each thread in the ta array by calling the start() method on each thread in a loop.

Each thread created using MyThread will increment the static count variable and print the resulting value. Since count is an AtomicInteger, the increment operation is atomic and thread-safe, which means that multiple threads can safely increment the variable without interfering with each other.

The order in which the threads execute is unpredictable, so the output may not be in order. However, each thread will print a unique value because of the incrementAndGet() method, which returns the new value of the AtomicInteger after the increment operation.

Therefore, the correct answer is A. The program prints 1 2 3, and the order is unpredictable.