java中的方法同步

PEN*_*NNY 2 java

如何在编写java同步代码时并行运行静态和非静态java同步方法?

public class Counter{

   private static count = 0;

   public static synchronized  getCount()
   {
      return this.count;
   }

   public synchronized setCount(int count)
   {
      this.count = count;
   }
}
Run Code Online (Sandbox Code Playgroud)

x4u*_*x4u 7

静态方法在类对象上同步,而非静态方法在调用它们的类的特定实例上同步.因此,它们可以并行执行,因为它们通常在不同的对象上同步.

在下面的示例staticMethod1中,与后者版本使用明确同步它们的对象基本相同,staticMethod2并且method1相同method2:

class MyClass
{
    static synchronized void staticMethod1()
    {
        doSomething();
    }

    static void staticMethod2()
    {
        synchronized( MyClass.class )
        {
            doSomething();
        }
    }

    synchronized void method1()
    {
        doSomething();
    }

    void method2()
    {
        synchronized( this )
        {
            doSomething();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)