当前位置:网站首页>Detailed explanation of volatile usage
Detailed explanation of volatile usage
2022-07-18 19:58:00 【Flowers fall in the rain】
1. volatile The role of
- Guaranteed visibility
- There is no guarantee of atomicity
- Prevent command rearrangement
2. Verification of visibility
class MyData{
volatile int number = 0;
public void addTo60(){
thie.number = 60;
}
}
public class VolatileDemo{
public static void main(String[] args) {
MyData myData = new MyData();
new Thread(()->{
try{
TimeUnit.SECONDS.sleep(3);}catch(InterruptedException e){
e.printStackTrace();}
myData.addTo60();
}, "AAA").start();
while(myData.number == 0) {
// No addition volatile Always carry out this cycle , Because the upper thread changes the value ,main Threads don't know
}
}
}
3. Verification of atomicity is not guaranteed
class MyData{
volatile int number = 0;
public void addTo60(){
thie.number = 60;
}
public void addPlusPlus(){
number++;
}
AtomicInteger atomicInteger = new AtomicInteger();
public void addMyAtomic(){
atomicInteger.getAndIncrement();
}
}
public class VolatileDemo{
public static void main(String[] args) {
MyData myData = new MyData();
for(int i = 0; i < 20; i++) {
new Thread(() -> {
for(int j = 1; j <= 1000; j++){
myData.addPlusPlus();
myData.addMyAtomic();
}
}, String.valueOf(i)).start();
}
// Let the above thread execute later
while(Thread.activeCount() > 2) {
Thead.yield();
}
System.out.println(myData.number); // volatile There is no guarantee of atomicity , So the final value is not 20000
System.out.println(myData.atomicInteger ); // You can guarantee atomicity , The value is 20000
}
}
4. Prevent command rearrangement
- The concept of instruction rearrangement : When a computer is executing a program , To improve performance , Compilers and processors rearrange instructions .
Source code ----> Compiler optimized rearrangement ----> A parallel rearrangement of instructions ----> Memory system rearrangement ----> The final instruction to be executed - Case study 1:
// In the case of multithreading, instruction rearrangement occurs , May be 1234,2134,1324
public void mySort(){
int x = 11; // sentence 1
int y = 12; // sentence 2
x = x + 5; // sentence 3
y = x * x; // sentence 4
}
- Case study 2:
int a, b, x, y = 0;
x = a; b = 1; // Threads 1
y = b; a = 2; // Threads 2
// x = 0, y = 0
// Possible execution after instruction rearrangement :
b = 1; x = a; // Threads 1
a = 2; y = b; // Threads 2
// x= 2 y = 1
边栏推荐
- 第一个大规模中文视频多模态相似度数据集
- 8. Island issue
- 4.连接已终止的线程(回收线程)
- 【剑指 Offer II 041. 滑动窗口的平均值】
- [200 routines OpenCV] 232. Méthode spectrale de caractérisation
- [MySQL project practical optimization] convert multiple rows of data into the same row and multiple columns for display
- OpenGL ES学习(6)——认识纹理
- Full marks for all! The Chinese team IMO won four consecutive titles, leading the second place South Korea by a big score
- [机缘参悟-45]:鬼谷子-第九权篇-因人说话,投其所好
- 并行及分布式框架
猜你喜欢

安利一款笔记工具---Obsidian

Foreigners still stayed 20 years ago

7.9哈希表(散列表)

The admission list of the junior class of the University of science and technology of China was announced: Zhejiang is crazy about winning 30% of the places, and there are 4 people in Xuejun middle sc

6. Thread cancellation

2022 Hangzhou future science and technology city digital economy talent Programming Competition

Interview micro service

Ci521 domestic 13.56MHz reader chip replaces cv520 compatible

Company equity distribution reference

死锁预防、死锁避免、死锁检测
随机推荐
低代码三部曲之起因
5. Thread separation
渐隐渐现1920-500(8)
3.终止线程
12.单调栈——解决接雨水和柱状图中的最大矩形等问题
Chapter I FPGA digital signal processing_ Digital mixing (NCO and DDS)
Vivado ROM IP core
1.自制脚本语言-第一章笔记
OpenGL ES学习(2)——顶点着色器和片元着色器
An Amway note taking tool -- Obsidian
11.滑动窗口的最大值——重要结构双端队列
Company equity distribution reference
中科大少年班录取名单公布:浙江狂揽三成名额,仅学军中学就有4人
Principles and factors of the design of the company's equity structure
[200 opencv routines] 232 Spectral method of feature description
2022 年度杭州未来科技城数字经济人才编程大赛
6. Violent recursion to dynamic planning
Activity的生命周期
How to use COE files of vivado
Share constantly, tread the waves | developers say · dtalk mid year appreciation