使方法同步或将同步块添加到方法中有区别吗?

时间:2013-02-15 17:34:16

标签: java multithreading synchronized

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

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

2 个答案:

答案 0 :(得分: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.");
    }
}

答案 1 :(得分:0)

不,正如你所说的那样没有区别,但是方法本来就是静态的,synchronized块会把封闭类的类对象作为锁。