Documentation

The Java™ Tutorials
Hide TOC
Synchronized Methods同步的方法
Trail: Essential Java Classes
Lesson: Concurrency
Section: Synchronization同步

Synchronized Methods同步方法

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:如果countSynchronizedCounter的实例,则使这些方法同步有两个效果:

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.同步构造函数没有意义,因为只有创建对象的线程才能在构造对象时访问它。


Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. 在构造线程之间共享的对象时,要非常小心,不要过早地“泄漏”对该对象的引用。For example, suppose you want to maintain a List called instances containing every instance of class. 例如,假设您想要维护一个名为instancesList,其中包含类的每个实例。You might be tempted to add the following line to your constructor:您可能想在构造函数中添加以下行:
instances.add(this);
But then other threads can use 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字段可以通过非同步方法安全地读取,一旦构建了对象)此策略是有效的,但可能会出现活性问题,我们将在本课后面看到。


Previous page: Memory Consistency Errors
Next page: Intrinsic Locks and Synchronization