volatile在JSR(是Java Specification Requests的缩写,意思是Java规范提案)中的定义:
The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.
The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.
A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable .
简单的翻译一下:
Java编程语言中允许线程访问共享变量。为了确保共享变量能被一致地和可靠的更新,线程必须确保它是排他性的使用此共享变量,通常都是获得对这些共享变量强制排他性的同步锁。
Java编程语言提供了另一种机制,volatile域变量,对于某些场景的使用这要比锁更加的方便。
可以把变量声明为volatile,以让Java内存模型来保证所有线程都能看到这个变量的一致的一个值。