2

Will these two code blocks behave equally? You may assume that those run methods are called from threads.

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

Or

static Object syncObject = new Object();

public void run() {
    synchronized(syncObject) {
        System.out.println("A thread is running.");
    }
}
user1420042
  • 1,689
  • 9
  • 35
  • 53

2 Answers2

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

is equvalent to:

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

and for your information:

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

is equvalent to:

public void run()
{
    synchronized(ClassName.class) // lock on the the current class (ClassName.class)
    {
        System.out.println("A thread is running.");
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 1
    Just one small note on this. I believe, having a synchronized method is a little bit more benefitial/defensive. It decreases a little bit chance that somebody unexperienced will add into method some code outside of synchronized block. – Victor Ronin Feb 15 '13 at 17:40
  • @VictorRonin +1 I agree. – Eng.Fouad Feb 15 '13 at 17:42
0

No, as you put it is no difference, but is the method would have been a static one, the synchronized block would have the class object of the enclosing class as the lock.

comanitza
  • 1,103
  • 2
  • 10
  • 17