Java 线程 wait() notify() 在一个方法中


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()没有达到wait().

这是怎么回事?

对我来说,实现此方法中的两个同步方法至关重要。

主线程执行一个帧,该帧在其中呈现图像。wait()方法是否有可能将框架引导到白色窗口?

SingleSNR 方法中的this和被覆盖的 run 方法中的this不是同一个对象(在 run 中,this指的是 Thread 的匿名子类)。 您需要确保通知wait的相同对象,该对象可用作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(); 
          }
        } 

两个"this"不一样,一个是Signal2NoiseRatio,一个是线程

最新更新