hagem
hagem

Reputation: 189

Java thread wait() notify() in one method

public class Signal2NoiseRatio
{
    public ImagePlus SingleSNR(ImagePlus imagePlus) throws InterruptedException
    {

        new Thread()
        { 
          @Override public void run() 
          { 
              for (int i = 0; i <= 1; i++)
              { 
                  System.out.println("in queue"+i);
              }

              synchronized( this ) 
              { 
                  this.notify(); 
              }
            } 
        }.start();


        synchronized (this) 
        {
        this.wait();
        }


        return imagePlusToProcess;
    }
}

notify() does not reach wait().

what's wrong here?

It is essential for me that both synchonized methods in this one method are implemented.

the main thread perform a frame which presents an image in it. Is it possible that the wait() method leads the frame to a white window?

Upvotes: 0

Views: 1152

Answers (2)

andy
andy

Reputation: 1356

two "this"s are not the same, one is Signal2NoiseRatio, one is the Thread

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 122364

this in the SingleSNR method and this in the overridden run method are not the same object (inside run, this refers to the anonymous subclass of Thread). You need to make sure you are notifying the same object you wait for, which is available as Signal2NoiseRatio.this:

      @Override public void run() 
      { 
          for (int i = 0; i <= 1; i++)
          { 
              System.out.println("in queue"+i);
          }

          synchronized( Signal2NoiseRatio.this ) 
          { 
              Signal2NoiseRatio.this.notify(); 
          }
        } 

Upvotes: 2

Related Questions