Volatile 关键字的作用是变量在多个线程之间可见。
class ThreadVolatileDemo extendsThread {public boolean flag = true;
@Overridepublic voidrun() {
System.out.println("开始执行子线程....");while(flag) {
}
System.out.println("线程停止");
}public void setRuning(booleanflag) {this.flag =flag;
}
}public classThreadVolatile {public static void main(String[] args) throwsInterruptedException {
ThreadVolatileDemo threadVolatileDemo= newThreadVolatileDemo();
threadVolatileDemo.start();
Thread.sleep(3000);
threadVolatileDem