0
//The below code is throwing illegalmonitorstate exception.
public class Multithreading implements Runnable {

    static int i=0;
    public boolean ist1=true;
    public boolean ist2=false;

    public static void main (String args[]){
        Multithreading ins= new Multithreading();
        Thread t1 =new Thread(ins);
        Thread t2 =new Thread(ins);
        t1.setName("Even");
        t2.setName("ODD");

        t1.start();
        t2.start();
    }  

    @Override
    // Wanted to right run method used by two threads to print
    // even and odd number in sequence 

    public void run() {

        while(i<=9){

            try{
                if(Thread.currentThread().getName().contains("Even")&& i%2==0){
                    System.out.println(Thread.currentThread().getName()+"________"+i);
                    i=i+1;
                    Thread.currentThread().wait(100);
                }
                // due to wait is not used with synchronized but
                // i am not able to correct it  

                if(Thread.currentThread().getName().contains("ODD") && i%2>=1){
                    System.out.println(Thread.currentThread().getName()+"________"+i);
                    i=i+1;
                    Thread.currentThread().wait(100);

                    //System.out.println(e);    
                }
            }catch(Exception e){
                System.out.println(e);  
            }
        }
    }
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Mark Ola
  • 305
  • 2
  • 12
  • 1
    What do you want to achieve? – Mohammad Ashfaq Dec 08 '14 at 07:39
  • Take a look at this StackOverflow question: [IllegalMonitorStateException on wait() call](http://stackoverflow.com/questions/1537116/illegalmonitorstateexception-on-wait-call) – Jonny Henly Dec 08 '14 at 07:50
  • I cant put sleep as it not allow me to print it in order. i want to write a single run that will be accessed by two threads and one will print even and one will print odd (in sequence). – Mark Ola Dec 08 '14 at 08:47
  • Thanks @JonnyHenly....It works...i am able to print as i wanted...thatks for ur help man.... – Mark Ola Dec 08 '14 at 08:55

1 Answers1

0

To pause a thread, you need to use Thread.sleep() in your case instead of wait().

Mikhail
  • 4,175
  • 15
  • 31