Why my boolean variable should be volatile while stopping thread loop? [duplicate]

心不动则不痛 提交于 2019-12-17 16:39:12

问题


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;
   }
}

And here is the Main class:

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?


回答1:


When Concurrent thread will cache running variable that means it will cache in thread working memory.

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




回答2:


with Volatile state will be updated straight away in main memory. So as soon as running is updated , concurrent thread will see the updated state instantaneously.

Update :- It's working properly in your case probably because you don't have good number of multiple threads or if you have then by that time state has been updated in main memory by then. Best way to observe this kind of behavior to set up load tests (using tools like Jmeter). This indicates that why having good hold on theoretical/basic concepts matters otherwise you get these kind of issues on production environment which breaks your head as some projects don't have budget/timelines to do load testing



来源:https://stackoverflow.com/questions/39558261/why-my-boolean-variable-should-be-volatile-while-stopping-thread-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!