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发行说明。
The java.util.concurrent.atomic
package defines classes that support atomic operations on single variables. java.util.concurrent.atomic
包定义了支持单变量原子操作的类。All classes have 所有类都有get
and set
methods that work like reads and writes on volatile
variables. get
和set
方法,它们的工作方式类似于对volatile
变量的读取和写入。That is, a 也就是说,set
has a happens-before relationship with any subsequent get
on the same variable. set
与同一变量上的任何后续get
具有“发生在之前”关系。The atomic 原子compareAndSet
method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables.compareAndSet
方法也具有这些内存一致性特性,适用于整数原子变量的简单原子算术方法也具有这些特性。
To see how this package might be used, let's return to the 要了解如何使用此包,让我们回到最初用于演示线程干扰的Counter
class we originally used to demonstrate thread interference:Counter
类:
class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }
One way to make 使Counter
safe from thread interference is to make its methods synchronized, as in SynchronizedCounter
:Counter
免受线程干扰的一种方法是使其方法同步,如SynchronizedCounter
:
class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
For this simple class, synchronization is an acceptable solution. 对于这个简单的类,同步是一个可接受的解决方案。But for a more complicated class, we might want to avoid the liveness impact of unnecessary synchronization. 但是对于一个更复杂的类,我们可能希望避免不必要的同步对活跃度的影响。Replacing the 使用int
field with an AtomicInteger
allows us to prevent thread interference without resorting to synchronization, as in AtomicCounter
:AtomicInteger
替换int
字段可以防止线程干扰,而无需借助同步,如AtomicCounter
所示:
import java.util.concurrent.atomic.AtomicInteger; class AtomicCounter { private AtomicInteger c = new AtomicInteger(0); public void increment() { c.incrementAndGet(); } public void decrement() { c.decrementAndGet(); } public int value() { return c.get(); } }