线程能够看到java中主线程设置的更新静态变量

sek*_*har 0 java static multithreading volatile

能否请您澄清代码有什么问题:

问:即使我没有将blinker声明为volatile,但是线程t1能够看到主线程设置的更新值(true)....

码:

package com.learning;
public class HowToStopRunningThread implements Runnable{
/**
* @param args
*/
public static boolean blinker;

public static void main(String[] args) {
Thread t = new Thread(new HowToStopRunningThread());
t.start();
HowToStopRunningThread obj = new HowToStopRunningThread();
obj.stop();
}

public void stop(){
try{
Thread.sleep(100);
System.out.println(“Setting the Blinker value”);
blinker = true;
}catch(InterruptedException ie){
ie.getMessage();
}
}


@Override
public void run() {
while(!blinker){
try{
System.out.println(“blinker:”+blinker);
Thread.sleep(1000);
}catch(InterruptedException ie){
ie.getMessage();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)

输出:

blinker:false
Setting the Blinker value
Run Code Online (Sandbox Code Playgroud)

-----------然后线程从while循环中出来

JB *_*zet 6

volatile 保证其他线程可以看到新值.但这并不意味着保证非易失性变量的变化是不可见的.

简而言之,这是偶然的,并不能保证始终在任何地方工作.

在这种情况下,它肯定有效,因为两个线程都打印到System.out,而println是一个同步方法.同步还提供可视性保证.