在编写java同步代码时,静态和非静态java同步方法如何并行运行?
public class Counter{
private static count = 0;
public static synchronized getCount()
{
return this.count;
}
public synchronized setCount(int count)
{
this.count = count;
}
}
最佳答案
静态方法在类对象上同步,而非静态方法在调用它们的类的特定实例上同步。因此它们可以并行执行,因为它们通常在不同的对象上同步。
在以下示例中,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();
}
}
}
关于java - java中的方法同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8213167/