相关疑难解决方法(0)

使用同步方法而不是同步块是否有优势?

任何人都可以通过一个例子告诉我同步方法优于synchronized块的优势吗?

java concurrency multithreading locking synchronized

397
推荐指数
13
解决办法
28万
查看次数

为什么Synchronized阻止比同步方法更好?

我已经开始在线程中学习同步.

同步方法:

public class Counter {

   private static int count = 0;

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

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

}
Run Code Online (Sandbox Code Playgroud)

同步块:

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

我什么时候应该使用Synchronized方法和Synchronized块?为什么Synchronized阻止比同步方法更好?

java multithreading synchronization

56
推荐指数
5
解决办法
9万
查看次数