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发行说明。
Consider a simple class called 考虑一个简单的叫做Counter
Counter
的类
class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }
Counter
is designed so that each invocation of increment
will add 1 to c
, and each invocation of decrement
will subtract 1 from c
. Counter
的设计使得每次调用increment
将向c
添加1,每次调用decrement
将从c
中减去1。However, if a 但是,如果Counter
object is referenced from multiple threads, interference between threads may prevent this from happening as expected.Counter
对象是从多个线程引用的,线程之间的干扰可能会阻止这种情况发生。
Interference happens when two operations, running in different threads, but acting on the same data, interleave. 当在不同线程中运行但作用于相同数据的两个操作交错时,就会发生干扰。This means that the two operations consist of multiple steps, and the sequences of steps overlap.这意味着这两个操作由多个步骤组成,并且步骤序列重叠。
It might not seem possible for operations on instances of Counter
to interleave, since both operations on c
are single, simple statements. Counter
实例上的操作似乎不可能交错,因为c
上的两个操作都是单个简单语句。However, even simple statements can translate to multiple steps by the virtual machine. 然而,即使是简单的语句也可以通过虚拟机转换为多个步骤。We won't examine the specific steps the virtual machine takes it is enough to know that the single expression 我们不会检查虚拟机采取的具体步骤单表达式c++
can be decomposed into three steps:c++
可以分解为三个步骤:
c
.c
的当前值。c
.c
。The expression 表达式c--
can be decomposed the same way, except that the second step decrements instead of increments.c--
可以用同样的方式分解,除了第二步是递减而不是递增。
Suppose Thread A invokes 假设线程A调用increment
at about the same time Thread B invokes decrement
. increment
的时间与线程B调用decrement
的时间大致相同。If the initial value of 如果c
is 0
, their interleaved actions might follow this sequence:c
的初始值为0
,则它们的交错操作可能遵循以下顺序:
Thread A's result is lost, overwritten by Thread B. 线程A的结果丢失,被线程B覆盖。This particular interleaving is only one possibility. 这种特殊的交织只是一种可能性。Under different circumstances it might be Thread B's result that gets lost, or there could be no error at all. 在不同的情况下,可能是线程B的结果丢失了,或者根本没有错误。Because they are unpredictable, thread interference bugs can be difficult to detect and fix.因为它们是不可预测的,所以线程干扰bug可能很难检测和修复。