(Original) four common methods to ensure JAVA thread security, java thread
There are many methods in Java to ensure thread security, such as using synchronous methods, synchronous blocks, atomic classes (atomic concurrent classes), implementing concurrent locks, and using volatile keywords, use the same class and thread security class.
Here is the most basic thread security tutorial
In fact, it is easy to misunderstand the use of volatile, so that volatile can be used for atomic operations. The Volatile variable hassynchronizedBut not atomic. This means that the thread can automatically discover the latest value of the volatile variable. Volatile variables can be used to provide thread security, but can only be used in a very limited set of Use Cases: There is no constraint between multiple variables or between the current value of a variable and the modified value of a variable. Therefore, using volatile alone is not enough to implement counters, mutex locks, or any class that has an Invariants related to multiple variables (such as "start <= end ").
For variables modified by volatile, the jvm Virtual Machine only ensures that the value loaded from the primary memory to the thread's working memory is up to date.
Directly run the Code:
Import java. util. concurrent. atomic. atomicInteger; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; public class Counter {public static int count = 0; // for value reference, the multi-thread operation is a copy of the variable, and the operation is refreshed to the primary storage. therefore, it is not atomic. // Incorrect volatile usage. volatil only performs memory address operations directly, but does not guarantee thread security. volatile is easily misused and used for atomic operations. public volatile static int volatileCount = 0; static Object obj = new Object (); public static AtomicInteger atomicCount; // correct method 1. Use an atom to operate static class MyObject {// correct method 4. Use address reference. multithreading uses address operations. The value is changed to the same variable (Address) static int mycount = 0;} public static void inc1 () {MyObject. mycount ++;} public static void inc () {// The delay here is 1 millisecond, making the result obviously try {Thread. sleep (1);} catch (InterruptedException e) {} // typical error 1: It is obviously incorrect to lock the resource object, actually meaningless // Lock lock = new ReentrantLock (); // lock. lock (); // synchronized (obj) // method 2, which can be used to perform block synchronization. This is also the most common method {count ++; volatileCount ++; atomicCount. incrementAndGet ();} // lock. unlock ();} public static void main (String [] args) {// start 100 threads simultaneously for I ++ computing, check the actual result atomicCount = new AtomicInteger (0); Lock lock = new ReentrantLock (); // correct method 3, reentrantLock Thread threads [] = new Thread [100]; for (int I = 0; I <100; I ++) {threads [I] = new Thread (new Runnable () {@ Override public void run () {// lock. loc K (); // method 3, which can be used to lock the ReentrantLock Counter. inc (); // lock. unlock (); inc1 () ;}}); threads [I]. start () ;}// ensure that all threads end for (int I = 0; I <100; I ++) {try {threads [I]. join ();} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/// if no synchronization lock exists. values may be different. System. out. println ("Run result 1: Counter. count = "+ Counter. count); // The atomicCount value should be consistent with the System. out. println ("result 2: Counter. atomicCount = "+ Counter. atomicCount); // The atomicCount value. If no synchronization lock is available, the value may be different. System. out. println ("running result 3: Counter. volatileCount =" + Counter. volatileCount); // use address reference. multithreading uses address operations. The value is changed to the same variable (address ). System. out. println ("running result 4: Counter. mycount =" + MyObject. mycount );}}
After running, the result may be as follows:
Result 1: Counter. count = 96
Result 2: Counter. atomicCount = 100
Result 3: Counter. volatileCount = 97
Running result 4: Counter. mycount = 100
If you cancel comments on lines 52 and 54 (or cancel comments on lines 32), the result must be as follows:
Result 1: Counter. count = 100
Result 2: Counter. atomicCount = 100
Result 3: Counter. volatileCount = 100
Running result 4: Counter. mycount = 100