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 programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. Java编程语言提供了两种基本的同步习惯用法:同步方法和同步语句。The more complex of the two, synchronized statements, are described in the next section. 下一节将描述这两个语句中更复杂的同步语句。This section is about synchronized methods.本节介绍同步方法。
To make a method synchronized, simply add the 要使方法同步,只需将synchronized
keyword to its declaration:synchronized
关键字添加到其声明中:
public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
If 如果count
is an instance of SynchronizedCounter
, then making these methods synchronized has two effects:count
是SynchronizedCounter
的实例,则使这些方法同步有两个效果:
Note that constructors cannot be synchronized using the 请注意,构造函数不能同步将synchronized
keyword with a constructor is a syntax error. synchronized
关键字与构造函数一起使用是一个语法错误。Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.同步构造函数没有意义,因为只有创建对象的线程才能在构造对象时访问它。
List
called instances
containing every instance of class. instances
的List
,其中包含类的每个实例。instances.add(this);
instances
to access the object before construction of the object is complete. instances
访问对象。Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through 同步方法支持防止线程干扰和内存一致性错误的简单策略:如果一个对象对多个线程可见,则对该对象变量的所有读取或写入都通过synchronized
methods. synchronized
方法完成。(An important exception: (一个重要的例外:构建对象后无法修改的final
fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness, as we'll see later in this lesson.final
字段可以通过非同步方法安全地读取,一旦构建了对象)此策略是有效的,但可能会出现活性问题,我们将在本课后面看到。