【问题标题】:Is there a difference between making a method synchronized or adding a synchronized block into the method? [duplicate]使方法同步或在方法中添加同步块之间有区别吗? [复制]
【发布时间】:2013-01-31 18:01:51
【问题描述】:

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

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

【问题讨论】:

  • 正如@Eng.Fouad 指出的那样,它们锁定了不同的对象。对吗?
  • 谢谢,发帖前我没有看到那篇文章(抱歉)。

标签: java multithreading synchronized


【解决方案1】:
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.");
    }
}

【讨论】:

  • 只是一个小注释。我相信,使用同步方法会更有益/更具防御性。它减少了一些没有经验的人在方法中添加同步块之外的一些代码的机会。
  • @VictorRonin +1 我同意。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-12
    • 2015-07-25
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2010-10-09
    • 2011-09-02
    相关资源
    最近更新 更多