Recently learning some knowledge of high concurrency, when learning to Atomic, run the program, not the same as expected
The code is as follows
Public classLearn13 {atomicinteger count=NewAtomicinteger (0); voidm () { for(inti= 0; i< 10000; i++) count.getandincrement (); } Public Static voidMain (string[] args) {FinalLearn12 Learn =NewLearn12 (); Runnable R=NewRunnable () {@Override Public voidrun () {learn.m (); } }; List<Thread> threads =NewArraylist<thread>(); for(inti= 0; i< 10; i++) {Threads.add (NewThread (R, "Thead" +i)); } for(Thread thread:threads) {Thread.Start (); } for(Thread thread:threads) {Try{thread.join (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println (Learn.count); }}
Example will be able to get 100000 results, but I did not get, each time is not the same, the method is not atomic operation, I do not know where there is a problem, I hope to see can help answer the next
About Java Atomic Package usage help