Java memory model and thread safety one, atomicity
atomicity means that an operation is non-interruptible. Even when multiple threads are executed together, an operation will not be disturbed by other threads once it is started.
Think: i++ is atomic manipulation?
Second, the Order of
Java code is executed in a way that does not perform in the semantic order in which the program is written (in order to optimize performance). Do not explain specifically.
Third, visibility
Visibility refers to a thread that modifies the value of a shared variable and whether other threads can immediately know the change.
Compiler optimizations
Hardware optimizations (e.g. write absorption, batch operation)
The visibility of the Java Virtual machine level
public class Visibilitytest extends Thread {
Private Boolean stop;
public void Run () {
int i = 0;
while (!stop) {
i++;
}
System.out.println ("Finish loop,i=" + i);
}
public void StoPit () {
Stop = true;
}
public Boolean getstop () {
return stop;
}
public static void Main (string[] args) throws Exception {
Visibilitytest v = new Visibilitytest ();
V.start ();
Thread.Sleep (1000);
V.stopit ();
Thread.Sleep (2000);
SYSTEM.OUT.PRINTLN ("Finish main");
System.out.println (V.getstop ());
}
Iv. Rules of Happen-before
Procedural Order Principle: the serialization of semantics within a thread
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 the 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
Java Concurrency Programming (iii) Java memory model and thread safety