Yuval Levy
Yuval Levy

Reputation: 2516

use of wait() and notify() in syncrhonized methods

If I wrote the following classes:

public class Thread1 extends thread{
  int num;
  OtherObject obj;
  boolean isFinished;
  public Thread1(int num, OtherObject obj){
    this.num = num;
    this.obj = obj;
    isFinished = false;
  }

  public void run(){
    this.startMethod();
  }

  public synchronize void startMethod(){
    obj.anotherMethod()
    if(isFinished !=true)
      wait();
    isFinished = true;
    notifyAll();
  }

public class main{
  public static void main (String[] args){
    OtherObject other = new OtherObject();
    Thread1 first = new Thread1(1, other);
    Thread1 second = new Thread1(2, other);
    first.start();
    second.start();

*this code doesn't has logic meaning, but to represent the idea of synchronized, wait(), notify().

1) When will the synchronized method run synchronized. "first" and "second" are different objects, so will they be synchronized? or not? or because they have shared variable - OtherObject obj they will be synchronized?

2) When I write wait() lets say for thread "first" the object will go to sleep and wake up when?

only when another object from the same class has done the notify()? or also when any object in the program will call notify()? and if I write the notify in "OtherObject" class it will also make "first" object to wake up?

3) The "startMethod" is synchronized, because of it, when I start() the first and second threads then they do the run method and start the "startMethod".

The "startMethod" will be done as synchronized or not? maybe because it goes to "anotherMethod" (that is not synchronized method) inside or because it started from "run" that is not synchronized also? I didn't understand when method that is marked as synchronized will be synchronized and in which circumstances it will stop being synchronized?

Upvotes: 0

Views: 98

Answers (1)

Ed Morales
Ed Morales

Reputation: 1037

3) The method is synchronized, but only to that object instance, both threads will run it without blocking each other since they are 2 separate instances.

2) If a thread uses wait (you have to have a lock first), it goes into waiting mode and only start again when another thread with the same lock uses notify/nofityAll. If a thread with a different lock calls notify, nothing will happen to that specific thread.

Side node: notify tells a single thread to continue but its chosen at random so many people prefer to use notifyAll.

1) if you want to be able to sync on a sharable variable you are looking to use this:

var Object obj; //assign instance on constructor or something like that

void method(){
    synchronized(obj){
         //sync code for obj instance
    }
}

Upvotes: 1

Related Questions