java - 为什么同步块(synchronized block)比同步方法更好?

标签 java multithreading synchronization

我已经开始学习线程同步了。

同步方式:

public class Counter {

   private static int count = 0;

   public static synchronized int getCount() {
      return count;
   }

   public synchronized setCount(int count) {
      this.count = count;
   }

}

同步块(synchronized block):

public class Singleton {

   private static volatile Singleton _instance;

   public static Singleton getInstance() {
      if (_instance == null) {
         synchronized(Singleton.class) {
            if (_instance == null)
               _instance = new Singleton();
         }
      }
      return _instance;
   }
}

什么时候应该使用 synchronized 方法和 synchronized block ?

为什么 synchronized block 比 synchronized 方法更好?

最佳答案

不是更好,只是不同。

当你同步一个方法时,你实际上是在同步到对象本身。在静态方法的情况下,您正在同步到对象的类。所以下面两段代码的执行方式相同:

public synchronized int getCount() {
    // ...
}

这就像你写的一样。

public int getCount() {
    synchronized (this) {
        // ...
    }
}

如果您想控制与特定对象的同步,或者您只想将方法的部分同步到该对象,则指定一个 synchronized block 。如果在方法声明中使用 synchronized 关键字,它会将整个方法同步到对象或类。

关于java - 为什么同步块(synchronized block)比同步方法更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906548/

相关文章:

java - Dining Philosophers 代码中发生的饥饿

java - OnSensorChanged线程

linux - 设置 Rsync 使用 cwrsync 从 Windows 拉取到 Linux Box

java - Spring 表单输入不能被禁用

java - TreeSet 上的迭代器导致无限循环

java - 我无法从 sqlite 解析日期。解析异常 : Unparseable date

c# - 使用线程和 EventWaitHandle 的生产者/消费者模式

plugins - 修复错误 : Plugin with id 'com.android.application' not found

java - volatile 和原子性在一起。这有什么意义吗?

java - 为什么 native String getBytes 方法比自定义实现的 getBytesFast 方法慢?