Refer to an example first http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html#!comments
Even if it is just i++, it is actually composed of multiple atomic operations: Read I, Inc., write I, if multiple threads are executing simultaneously i++,volatile can only guarantee that the I that they operate is the same piece of memory, but it is still possible to write dirty data. If you add atomic wrapper classes with Java 5, you do not need sychronized for operations such as their increase.
Using Atomicinteger, it encapsulates the atomic operations of some integers and makes them thread-safe
Packagethreadtest;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.atomic.AtomicInteger; Public classAtomicIntegerTestApp1 { Public StaticAtomicinteger count =NewAtomicinteger (0); Public Static voidInc () {//count++;Count.incrementandget (); } Public Static voidMain (string[] args)throwsinterruptedexception {executorservice service=Executors.newfixedthreadpool (Integer.max_value); for(inti = 0; I < 10000; i++) {Service.execute (NewRunnable () {@Override Public voidrun () {threadpooltestapp1.inc (); } }); } service.shutdown (); //give a close time (timeout), but the actual shutdown time should be this smallService.awaittermination (300, Timeunit.seconds); System.out.println ("Run Result: counter.count=" +threadpooltestapp1.count); }}
Atomic operations in Java include the following:
1) Assignment operation of basic types except long and double
2) All assignment operations that reference reference
3) java.concurrent.atomic.* All operations of all classes in the package
Count++ is not an atomic operation, it is a combination of 3 atomic operations
1. Read the Count value in main memory and assign the value to a local member variable TMP
2.tmp+1
3. Assign TMP to count
Thread-safe Atomic wrapper classes Example