The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
In programming, an atomic action is one that effectively happens all at once. 在编程中,原子行为是一种有效地同时发生的行为。An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. 原子行为不能中途停止:要么完全发生,要么根本不发生。No side effects of an atomic action are visible until the action is complete.在动作完成之前,不会看到原子动作的副作用。
We have already seen that an increment expression, such as 我们已经看到,增量表达式,例如c++
, does not describe an atomic action. c++
,并没有描述原子的动作。Even very simple expressions can define complex actions that can decompose into other actions. 即使是非常简单的表达式也可以定义可以分解为其他动作的复杂动作。However, there are actions you can specify that are atomic:但是,您可以指定一些原子操作:
long
and double
).long
和double
之外的所有类型),读和写都是原子的。volatile
(including long
and double
variables).volatile
的变量(包括long
和double
变量),读写都是原子的。Atomic actions cannot be interleaved, so they can be used without fear of thread interference. 原子操作不能交错,因此它们可以在不担心线程干扰的情况下使用。However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. 然而,这并不能消除同步原子操作的所有需要,因为内存一致性错误仍然是可能的。Using 使用volatile
variables reduces the risk of memory consistency errors, because any write to a volatile
variable establishes a happens-before relationship with subsequent reads of that same variable. volatile
变量可以降低内存一致性错误的风险,因为对volatile
变量的任何写入都会与该变量的后续读取建立“发生在之前”的关系。This means that changes to a 这意味着对volatile
variable are always visible to other threads. volatile
变量的更改对其他线程总是可见的。What's more, it also means that when a thread reads a 更重要的是,这还意味着当线程读取volatile
variable, it sees not just the latest change to the volatile
, but also the side effects of the code that led up the change.volatile
变量时,它不仅看到volatile
的最新更改,还看到导致更改的代码的副作用。
Using simple atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors. 使用简单的原子变量访问比通过同步代码访问这些变量更有效,但需要程序员更加小心以避免内存一致性错误。Whether the extra effort is worthwhile depends on the size and complexity of the application.额外的工作是否值得取决于应用程序的大小和复杂性。
Some of the classes in the java.util.concurrent
package provide atomic methods that do not rely on synchronization. java.util.concurrent
包中的一些类提供了不依赖于同步的原子方法。We'll discuss them in the section on High Level Concurrency Objects.我们将在高级并发对象一节中讨论它们。