IllegalMonitorStateException in Thread wait notify



我正在处理一项任务,其中我有 n 个线程,每个线程将按顺序打印第 n 个数字[1 到 n].每个线程都在等待并相互通知。
例如:-
如果我们有 6 个线程,那么第一个线程应该打印 1,第二个线程应该打印 2,依此类推。[顺序 1 至 6]
当我在程序下面运行时,我得到非法监视器状态异常。

package interviews;
public class NumerPrintingwithThreadCount {
public static void main(String[] args) throws InterruptedException {
    int Max =6;
    Integer [] o = new Integer [Max];
    for (int i = 0; i < Max; i++) {
        o[i] = new Integer(i);
    }
    PrintingThread []tt = new PrintingThread [Max];
    for (int i = 0; i <Max; i++) {
        Integer obj1 =o[i];
        Integer obj2=null;
        if(i==Max-1){
        obj2 = o[0];
        }
        else{
        obj2=o[i+1];
        }
        PrintingThread t=new PrintingThread(obj1, obj2,0);
        tt[i]=t;
    }
    for (int i=tt.length-1; i >=0; i--) {
        tt[i].setName("Thread"+1);
        tt[i].start();
        Thread.sleep(1);
    }  
}
}  
class PrintingThread extends Thread{
    Integer object1=null;
    Integer object2=null;
    int min =0;
    public PrintingThread(Integer obj1 ,Integer obj2, int min) {
        this.object1=obj1;
        this.object2=obj2;
        this.min=min;
    }
    public void run() {
        try {
            if(min==object1.intValue())
            {
                object2.notify();
            }else{
                synchronized (object2) {
                    object2.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName());
            object2.notify();
    }
}

来自 Javadoc for Object.notify((

此方法应仅由作为 所有者的线程调用 此对象的监视器。线程成为对象的所有者 通过以下三种方式之一进行监视:

  • 通过执行该对象的同步实例方法。
  • 通过执行在对象上同步的同步语句的主体。
  • 对于 Class 类型的对象,通过执行该类的同步静态方法。

您必须同步要对其调用通知的对象。

注意:由于wait((可能会错过通知或虚假唤醒,因此您应该将状态更改与通知/等待相关联。 即在 wait(( 上检查状态更改并在 notify(( 上引入状态更改

最新更新