gpt4 book ai didi

java - volatile 关键字: Need explanation for this program behaviour

转载 作者:行者123 更新时间:2023-12-01 20:27:08 27 4
gpt4 key购买 nike

通过该程序理解 volatile 关键字:

public class VolatileExample implements Runnable{    
private volatile int vol;
@Override
public void run(){
vol=5;
while(vol==5)
{
System.out.println("Inside run when vol is 5. Thread is : "+Thread.currentThread().getName());
if("t2".equals(Thread.currentThread().getName()))
{
System.out.println("Got Thread : "+Thread.currentThread().getName()+" Now Calling Stop To End This Flow");
stopIt();
}
}
}
public void stopIt(){
vol=10;
}

public static void main(String[] args){
VolatileExample ve1 = new VolatileExample();
VolatileExample ve2 = new VolatileExample();

Thread t1 = new Thread(ve1);
Thread t2 = new Thread(ve1); //t1 and t2 operate on same instance of VolatileExample class

t1.setName("t1");
t2.setName("t2");

t1.start();
t2.start();
}
}

输出:

Inside run when vol is 5. Thread is : t1
Inside run when vol is 5. Thread is : t1
Inside run when vol is 5. Thread is : t2
Inside run when vol is 5. Thread is : t1
Got Thread : t2 Now Calling Stop To End This Flow
Inside run when vol is 5. Thread is : t1

对 vol 变量的所有写入都将立即写入主内存,并且应该立即对其他线程“可见”。为什么调用 stopIt() 后 t1 线程仍然执行?难道它看不到 vol 值现在是 10 而不是 5 吗?

最佳答案

没有证据表明 t1 在调用 stopIt() 后运行。

事情可能按这个顺序发生

     t1                     t2
System.out.println("calling stopIt()");
while(vol==5)
System.out.println("Inside run")
enter stopIt()
vol = 10

这会给你你观察到的结果。 (还有其他可能的排序方式可以给您带来这个结果。)

关于java - volatile 关键字: Need explanation for this program behaviour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43732734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com