//一下代码主要阐述volatiile的作用
package com.example.demo; public class Test { public static void main(String[] args) { Aboing a = new Aboing(); a.start(); // synchronized (a){ while (true){ if(a.isFlag()){ System.out.println("nice"); } } // } } } class Aboing extends Thread{ private volatile boolean flag = false;//volatile 保证主内存为最新变量值 public boolean isFlag(){ return flag; } @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } flag = true; System.out.println("flag = "+ flag); } }
1:volatile可以理解成轻量的sychronized
2: 都可以将实例和非私有变量强制刷新到主内存中