java - Behavoir of Threads with AtomicInteger -
the following problem on mock exam ocp java se 7 programmer ii exam. solution says answer 0, colleagues , not sure answer isn't between -5 , 5 (which choice) clarify us? here code:
import java.util.concurrent.atomic.atomicinteger; class atomicvariabletest { 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 = 0; < 5; i++) { new incrementer().start(); new decrementer().start(); } system.out.println(counter); } }
thanks!
running multiple times logs shows order in threads ran change outcome. on multiple runs, did 0, results experimentally varied -1 2 on machine. valid answer : between -5 , 5.
class atomicvariabletest { private static atomicinteger counter = new atomicinteger(0); static class decrementer extends thread { public void run() { counter.decrementandget(); // #1 system.out.println("dec"); } } static class incrementer extends thread { public void run() { counter.incrementandget(); // #2 system.out.println("inc"); } } public static void main(string[] args) { (int = 0; < 5; i++) { new incrementer().start(); new decrementer().start(); } system.out.println(counter); } }
output of program looking :
inc dec inc dec inc dec inc dec 0 inc dec
dec -1 inc dec inc dec dec dec inc inc inc
Comments
Post a Comment