First, the atomic nature
Atomicity means that an operation is non-interruptible. Even when multiple threads are executing together, an operation will not be disturbed by other threads once it is started.
i++是原子操作吗?不是,包含3个操作:读i,i=i+1,写i32位的机子上读取64位的long型也不是原子操作
Second, the order of 2.1 examples
During concurrency, the execution of the program may occur in a disorderly sequence
2.2 Steps
The execution of an instruction can be divided into a number of steps:
- Take a reference to the IF
- Decoding and fetching register operand IDs
- Perform or valid address calculation ex
- Memory Access Mem
- Write back WB
Pipeline Execution Instructions
Analysis:
指令分解成不同阶段假设一条指令消耗一个CPU时钟周期5个人生产一个产品,5个人同时工作a=b+c读b读c计算b+c,结果放到a写a
Analysis:
进行优化,使气泡尽可能的少
Analysis:
调整指令顺序,可以消除气泡
Third, Visibility 3.1 definition
Visibility is a batch when a thread modifies the value of a shared variable, whether another thread can immediately know the change.
- Compiler optimizations
- Hardware optimizations (e.g. write absorption, batch operation)
批量操作,把操作进行积累,只把最终结果写入
3.2 The visibility of Java virtual machine levels
http://hushi55.github.io/2015/01/05/volatile-assembly
Public classVisibilitytestextendsThread {Private BooleanStop Public void Run() {inti =0; while(!stop) {i++; } System. out.println("Finish loop,i="+ i); } Public void StoPit() {stop =true; } Public Boolean Getstop() {returnStop } Public Static void Main(string[] args)throwsException {Visibilitytest v =New visibilitytest(); V.Start(); Thread.Sleep( +); V.StoPit(); Thread.Sleep( -); System. out.println("Finish Main"); System. out.println(v.Getstop()); }}
Analysis:
stop变量加volatile就不会有这个问题了
Iv. Happen-before
V. Thread Safety Concepts
When a function or library is called in a multithreaded environment, it can correctly handle the local variables of each thread, so that the program function is completed correctly.
i++ access in multi-threaded situations:
Java High concurrency-java memory model and thread safety