简体   繁体   中英

IllegalMonitorStateException in Thread wait notify

I am working on one task where i am having n threads and each thread will print nth number sequentially[1 to n] .where each thread is waiting and notifying each other .
for Ex:-
if we are having 6 Threads then 1st thread should print 1,2nd thread should print 2 and so on.[in sequence 1 to 6]
when i am running below program i am getting IllegalMonitorStateException .

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();
    }
}

From the Javadoc for Object.notify()

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

You must synchronize the object you are calling notify on.

Note: as wait() can either miss a notify or wake spuriously, you should associate a state change with a notify/wait. ie check the state change on wait() and introduce a state change on notify()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM