Atomic Nature
Atomicity means that an operation is non-interruptible. Even when multiple threads are executed together, the operation will not be disturbed by other threads once it is started. That is, an atomic operation is a small operation.
For example, i++, actually experienced reading, calculation, assignment is definitely not an atomic operation. An assignment operation such as I = 10 can be called an atomic operation.
The Java.util.comcurrent.atomic bag is all about atomic operations, and there's time to write another blog post.
Order of
When it comes to ordering, it inevitably has a disorderly order, which is caused by the JVM's command rearrangement optimization.
If we want to keep order completely, we need to add a synchronous lock (synchronized) to the object, which is actually a single thread execution.
Visibility of
Visibility is when a thread modifies the value of a shared variable, and whether another thread can immediately know the change.
While other threads do not see the fact that each CPU has a register, one thread modifies the value in the register and commits it to the JVM, and there is a cache of data in the registers of the CPU, and when it looks back at the JVM, it finds that the value has changed.
Java provides the volatile keyword to ensure visibility.
When a shared variable is modified by volatile, it guarantees that the modified value is immediately updated to main memory, and when other threads need to read it, it will read the new value in RAM.
Here's a piece of code to do the test.
Public classVisibilitytestextendsthread{
If there is no keyword volatile, it will be found that the thread can not be stopped, self-testing. Private volatile Booleanstop; Public voidrun () {inti = 0; while(!stop) {i++; } System.out.println ("Finish loop,i=" +i); } Public voidStoPit () {Stop=true; } Public BooleanGetstop () {returnstop; } Public Static voidMain (string[] args)throwsinterruptedexception {visibilitytest visibilitytest=Newvisibilitytest (); Visibilitytest.start (); Visibilitytest.sleep (1000); Visibilitytest.stopit (); System.out.println (Visibilitytest.getstop ()); }}
Happen-before Principles
? Sequence of procedures principle: a thread that guarantees semantic serialization A=1 b=a+1
? Volatile rules: The write of volatile variables, which occurs first in the read, which guarantees the visibility of volatile variables
? Lock rule: Unlocking (unlock) must occur before the subsequent locking (lock)
? Transitivity: A precedes b,b before C, then a must precede C
? The start () method of a thread precedes each of its actions? All operations of the thread precede the end of the thread (Thread.Join ())
? Thread Interrupt (interrupt ()) precedes the code of the interrupted thread
? Object constructor execution ends before the Finalize () method
Atomicity, ordering, visibility, and happen-before principles of Java concurrency