Consider the following program and choose the correct option:
import java.util.concurrent.atomic.AtomicInteger; public class Main { private static AtomicInteger counter = new AtomicInteger(0); static class Decrementer extends Thread { public void run() { counter.decrementAndGet(); // #1 }/*from www. j a va2s.c o m*/ } static class Incrementer extends Thread { public void run() { counter.incrementAndGet(); // #2 } } public static void main(String[] args) { for (int i = 0; i < 5; i++) { new Incrementer().start(); new Decrementer().start(); } System.out.println(counter); } }
a)this program will always print 0 b)this program will print any value between -5 to 5 c)If you make the run() methods in the Incrementer and Decrementer classes synchronized, this program will always print 0 d)the program will report compilation errors at statements #1 and #2
b)
You have employed AtomicInteger, which provides a set of atomic methods such as incrementAndGet()
and decrementAndGet()
.
hence, you will always get 0 as the final value of counter.
however, depending on thread scheduling, the intermediate counter values may be anywhere between -5 to +5, hence the output of the program can range between -5 and +5.