volatile修饰的变量可在多个线程间可见。
如下代码,在子线程运行期间主线程修改属性值并不对子线程产生影响,原因是子线程有自己独立的内存空间,其中有主内存中的变量副本。
1 public class RunThread extends Thread{ 2 3 private volatile boolean isRunning = true; 4 private void setRunning(boolean isRunning){ 5 this.isRunning = isRunning; 6 } 7 8 public void run(){ 9 System.out.println("进入run方法.."); 10 int i = 0; 11 while(isRunning == true){ 12 //.. 13 } 14 System.out.println("线程停止"); 15 } 16 17 public static void main(String[] args) throws InterruptedException { 18 RunThread rt = new RunThread(); 19 rt.start(); 20 Thread.sleep(1000); 21 rt.setRunning(false); 22 System.out.println("isRunning的值已经被设置了false"); 23 } 24 25 26 }