当前位置:网站首页>Multithreading 04 -- order of threads
Multithreading 04 -- order of threads
2022-07-22 20:53:00 【fengxianaa】
Last one :https://blog.csdn.net/fengxianaa/article/details/124425522
We all know java The code is executed sentence by sentence , Look at the following code :
public static void test(){
int val = 1; //code1
boolean bool = true; //code2
}
Above code ,code1 stay code2 Before , however JVM There is no guarantee when this code is actually executed code1 It will be there. code2 Go ahead , Because it could happen here Instruction reordering .
When a computer is executing a program , To improve performance , Compilers and processors often rearrange instructions :
Source code -> Compiler optimized rearrangement -> A parallel rearrangement of instructions -> Memory system rearrangement -> Final execution instruction
- Compiler optimized reordering : Compiler without changing the semantics of single thread program , You can rearrange the execution order of statements .
- Instruction level parallel reordering : Modern processors use instruction level parallelism to execute multiple instructions in an overlapping way . If there is no data dependency , The processor can change the execution order of machine instructions corresponding to statements .
- Reordering of memory system : Because the processor uses cache and read / Write buffer , This makes loading and storage operations appear to be out of order .
Although there is no guarantee that the execution order is consistent with the code order , But it promises Single thread The final execution result of the next program is consistent with the result of the sequential execution of the code . Above code ,code1 and code2 Which method is executed first does not affect the execution result of the whole method .
stay Java In memory model , Allow compiler and processor to reorder instructions , But the reordering process will not affect the execution results of a single thread , But it will affect the results of multi-threaded concurrent execution .
In the case of multithreading :
public class Demo3 {
static int x = 0, y = 0;
static int a = 0, b = 0;
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i < 10000; ++i){
x = 0; y = 0; a = 0; b = 0;
Thread one = new Thread(new Runnable() {
public void run() {
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
public void run() {
b = 1;
y = a;
}
});
one.start();other.start();
one.join();other.join();
if(x==0 && y==0){
System.out.println(" Reorder ");
}
}
}
}
// In a multiple cpu In the environment , Even if the above code is output “ Reorder ”, Nor does it reflect reordering , Because of working memory
Can pass synchronized and Lock To ensure order , It can also be done through volatile Keywords to ensure a certain “ Orderliness ”.
As for how to guarantee , First look at the following code
Single case ----DCL(Double Check Lock)
public class Singleton {
private int val;
private Singleton() {
val = 10;
}
private static Singleton instance;
public Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
Above code , In the case of high concurrency, problems may occur first . The problem lies in :instance = new Singleton(); This code .
This statement actually contains three instructions :
memory =allocate(); //1: Allocate memory space for objects
ctorInstance(memory); //2: Initialize object
instance =memory; //3: Set up instance Points to the memory address just allocated
among 2、3 The execution order of is interchangeable .
use volatile modification instance Variable , You can ban 2 and 3 Reorder .
Why? volatile You can disable reordering of instructions ?
By providing “ Memory barrier ” To prevent instructions from being reordered , In order to achieve volatile Memory semantics of , When the compiler generates bytecode , The memory barrier is inserted into the instruction sequence .
Memory barrier : For cross processor read and write operations , It is inserted between two instructions , The function is to prevent the compiler and processor from reordering
But not all code can be reordered :
public static void test(){
int val = 1; //code1
boolean bool = true; //code2
val +=1; //code3
int age = val; //code4
}
Above code ,code3 and code4 The order of execution cannot be interchanged . Because reordering will consider the relationship between instructions Data dependency .
边栏推荐
- 具有非矩形布局1结构的电流镜的梯度灵敏度降低
- 动态规划入门
- 信号处理:<三> DFT和FFT
- 文件
- 【面试:基础篇04:插入排序】
- MySQL connection failure solution
- 多线程06--CountDownLatch、CyclicBarrier、Semaphore
- Parasitic sensing common centroid binary weighted capacitor layout generation integrates layout, wiring, and cell capacitor size
- Redis 系列15--Redis 缓存清理
- Data transfer from one Mysql to another MySQL
猜你喜欢
随机推荐
Jmeter性能测试
【面试:基础篇05:快速排序】
Intensive reading of Detr paper and analysis of model structure
[FPGA]: IP Core - - DDR3
Monkey 介绍及使用
VIM configuration
多线程02--顺序执行和停止线程
初次见面 多多关照
字符串split操作到底有多少坑
Common centroid layout of active and passive equipment: review and future road
Spark Learning sparksql
mysql使用常见问题
1087 all roads lead to Rome (30 points)
ADB自动化测试框架
C language bitfield
spark常见问题
APP专项测试
Airtest conducts webui automated testing (selenium)
Redis series 11 -- redis persistence
A new checkerboard placement and sizing method for capacitors in charge scaling DAC based on nonlinear worst-case analysis