2

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

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.");
    }
}
4

2 回答 2

6
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.");
    }
}
于 2013-02-15T17:35:22.657 回答
0

不,正如您所说的那样,没有区别,但是如果该方法是静态方法,则同步块会将封闭类的类对象作为锁。

于 2013-02-15T17:39:49.770 回答