OCP Question 35, Explanation

Given the code fragments:

class Sprinter implements Runnable {
    private static AtomicInteger place = new AtomicInteger(0);
    public void run() {
        int p = place.incrementAndGet();
        System.out.print(p + " ");
    }
}

and

Thread justin1 = new Thread(new Sprinter());
Thread christian2 = new Thread(new Sprinter());
Thread usain3 = new Thread(new Sprinter());
Thread[] sprint = {justin1, christian2, usain3};
for (int i = 0; i < 3; i++) {
    sprint[i].start();
}

Which statement is true?

A. The program prints 1 2 3 and the order is unpredictable.
B. The program prints 1 2 3.
C. The program prints 1 1 1.
D. A compilation error occurs.

 

The correct answer is A.

The AtomicInteger class simply makes sure that while an int is being changed by a thread, no other thread can interfere in the process. On the other hand, the order in which threads get to work on that int is determined by the operating system at the runtime. There are many ways to ensure particular order of thread execution such as wait/notify mechanism, etc. Jeff Friesen has here a very nice article covering these aspects.

Leave Comment

Your email address will not be published.