Consider the following code and choose the best option:
import java.util.concurrent.atomic.AtomicInteger; class Main {/*from w w w. j a va2s. c om*/ private static AtomicInteger counter = new AtomicInteger(0); static class Decrementer extends Thread { public void run() { counter.decrementAndGet(); // #1 } } 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); } }
run()
methods in the Incrementer
and Decrementer
classes synchronized, this program will always print 0.a)
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, but the final value of the counter will always be 0.
So no synchronization is needed between the threads, although they access/modify a common variable.