Understand multithreading volatile keyword

1.java memory model
java in each sub-thread has a working memory, the main thread has a main memory. If the main memory in a static variable a = 0, then the child thread will read a variable on their work memory before use, when the child thread used, it will be taken out to use their working memory variables .
2.java memory model in synchronous interaction protocol, 8 atomic predetermined
@ 1.lock: The main variables in memory lock, a thread exclusive
@ 2.unlock: unlocking the lock applied, then the other the thread can have the opportunity to access this variable.
@ 3.read: variable acting on the main memory, the main memory of the working memory variable values read
@ value 4.load role in working memory, the read read read a copy of the variable work yo-memory.
@ 5.use: the role of the working memory variable, the value is passed down the thread code execution engine.
@ 6.assign: the role of the working memory variable, the execution engine processes the returned value to recopy copy of the variable.
@ 7.store: the role of the working memory variable, the value of the variable copy is transmitted to the main memory.
@ 8.write: variable acting on the main memory, store the value transmitted by the shared variable is written in the main memory.
3. practices:
. @ 1 Main - "read and then the first sub-load, the sub -" first main store, in wirte.
@ 2 did assign operation must be synchronized back to main memory, did not do assgin, synchronized back to main memory.
4. How to ensure visibility
@ 1.final variable
@ 2.synchronized sync blocks
@ 3.volatile modified
5.synchronized how to achieve visibility? (Multi-thread synchronization control)
@ 1. Before entering the synchronized block, first empty the shared variable in the working memory, re-loaded from the main memory
@ 2. Unlock the front must modify the shared variable synchronization back to main memory.
The role of 6.volatile keyword:
. @ 1 variable to ensure visibility
. @ 2 partial restriction code instructions reordering (jvm code optimization will reorder)
7.volatile how to ensure the visibility of the variables?
@ 1. When using volatile variables must be re-loaded from the main memory, and read, load continuous.
@ 2. After modifying volatile variable must be immediately synchronized back to main memory, and the store, write is continuous.
8.voliate difference in sychronized
@ 1. Use volatile than sychronized simple
@ 2.volatile slightly better performance than sychronized
usage scenarios (multi-threaded) 9.volatile
@ 1. Only one modified by multiple users
@ 2 overhead lower "read - write" locking strategy
, such as:
Private volatile int value;
public int the getValue () {
return value;
}
public int the synchronized INCREMENT (int NUM) {
return value ++;
}

Guess you like

Origin blog.csdn.net/weixin_39507514/article/details/88793491