1

I am a bit confused about synchronized-blocks in Java.

If one thread enters a synchronized-block of an instance of a class, can other threads use synchronized-methods of the same instance of the same class?

void myMain() {
    synchronized(this) {
        while(suspendFlag)
             wait();
        }
    }
}

synchronized void mysuspend() {
    suspendFlag = true;
}
SirFartALot
  • 1,215
  • 5
  • 25
neo360
  • 49
  • 5
  • yes they can. Synchronized method and synchronized statements are functionally equivalent. – Alexei Kaigorodov May 14 '19 at 16:41
  • The answer is no, because both `synchronized` area from your code lock on the instance itself. Thus other threads can't access it while current thread is executing in any of the 2 `synchronized` area. But, the current thread itself can, that's called `re-entrant`. – Eric May 16 '19 at 06:47

2 Answers2

1
synchronized void mysuspend(){
    suspendFlag = true;
}

is equivalent to

void mysuspend(){
    synchronized(this) {
        suspendFlag = true;
    }
}

So in your code it is not possible that one thread enters a synchronized block of an instance of a class and other threads use synchronized method mysuspend()

SirFartALot
  • 1,215
  • 5
  • 25
shani klein
  • 334
  • 1
  • 2
  • 14
0

Yes, because they are independently callable. A thread is not attached to a class or an instance of it. Each method of a class may be called independently from different threads.

What can limit this independence are synchronized methods. They are shortcuts for synchronized(this) {...} as method body.

Whenever a synchronized block is entered, the monitor on the associated instance is held.

A wait() frees the monitor on the surrounding synchronized block again, so other synchronized blocks can be executed.

There is a problem with your code: wait() will wait until a notify() on the monitor is called. But in your code neither a notify() is called, nor has the wait() a timeout.

Your while(suspendFlag) wait(); will then wait forever...

SirFartALot
  • 1,215
  • 5
  • 25
  • I did not copy the whole file. Before the synchronized block, Thread.sleep(200); is added. It is used by one thread. And mysuspend() is used by the main thread. And this method is preceded by Thread.sleep(1000); – neo360 May 14 '19 at 08:36
  • `sleep()` does not end a `wait()`. Only `notify()` or `wait(timeout)` after the timeout will. You can have a look at https://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep which explains some things.. – SirFartALot May 14 '19 at 09:09
  • 1
    @neo360, Don't try to _describe_ your code, and especially, don't try to describe it in a comment. If there's something you haven't already shown that would better explain your question, then edit the question, and add the actual code. – Solomon Slow May 14 '19 at 12:41