質問

Suppose my Foo class looked like this

public class Foo
{
    public static void func_1() { /* do something */ }
    public static void func_2() { /* do something */ }
}

and that my Bar class looked like this

public class Bar
{
    public void method_1()
    {
         synchronized(Foo.class)
         {
             Foo.func_1();
         } 
    }          
}

Now instead of locking Foo.class object in Bar.method_1, could I have declared Foo.func_1 and Foo.func_2 as synchronized, and still archived the same purpose?

Thank you

役に立ちましたか?

解決 2

Yes, they achieve the same thing -- locking Foo.class. Here's the relevant excerpt from the Java Language Specification, Section 8.4.3.6:

For a class (static) method, the monitor associated with the Class object for the method's class is used.

Using synchronized on the static func_1() or func_2() methods in your Foo class locks the Foo.class implicitly, while synchronized(Foo.class) locks it explicitly.

他のヒント

A static synchronized method obtains lock on class and by taking lock on Foo.class , you are doing same thing. So yes they will achieve same thing.

Yes they are pretty much the same. The only difference is : in one case lock is acquired before calling the method and in another it is acquired later.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top