使方法同步或在方法中添加同步块之间有区别吗



这两个代码块的行为是否相同?您可以假设这些运行方法是从线程中调用的。

public synchronized void run() {
    System.out.println("A thread is running.");
}

static Object syncObject = new Object();
public void run() {
    synchronized(syncObject) {
        System.out.println("A thread is running.");
    }
}
public synchronized void run()
{
    System.out.println("A thread is running.");
}

相当于:

public void run()
{
    synchronized(this) // lock on the the current instance
    {
        System.out.println("A thread is running.");
    }
}

供您参考:

public static synchronized void run()
{
    System.out.println("A thread is running.");
}

相当于:

public void run()
{
    synchronized(ClassName.class) // lock on the the current class (ClassName.class)
    {
        System.out.println("A thread is running.");
    }
}

不,正如你所说,这没有什么区别,但如果方法是静态的,那么同步块将把封闭类的类对象作为锁。

最新更新