为什么我的布尔变量在停止线程循环时应该是可变的? [英] Why my boolean variable should be volatile while stopping thread loop?
问题描述
假设我有一个包含while循环的线程,而我想从外部"停止它.
Let's say I have a thread including while loop and I want to stop it "from outside".
public class MyThread extends Thread {
private boolean running = true;
@Override
public void run() {
while (running) {
// do something
}
}
public void setRunning(boolean running) {
this.running = running;
}
}
这是Main类:
public class Main {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
// do something
mt.setRunning(false);
}
}
似乎正常停止了,但是我读过布尔值也应该是易变的.为什么?会加快停车速度吗?
It seems to be stopping properly, but I have read that the boolean should be also volatile. Why? Will it quicken the stopping?
推荐答案
当并发线程将缓存运行变量时,这意味着它将缓存在线程工作内存中.
When Concurrent thread will cache running variable that means it will cache in thread working memory.
Java中的volatile关键字用作Java编译器和Thread的指示符,它们不缓存此变量的值,并且始终从主内存中读取它.因此,如果您要共享实现中读写操作是原子性的任何变量,则必须声明为易失性变量.
The volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation you have to declare as volatile variable.
您可以通过下面的图片了解一个好主意
you can have good idea in you look into the below picture
这篇关于为什么我的布尔变量在停止线程循环时应该是可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!