请帮我解决代码中的非法监控异常

时间:2014-12-08 07:33:46

标签: java multithreading

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

1 个答案:

答案 0 :(得分:0)

要暂停某个帖子,您需要在案例中使用Thread.sleep()而不是wait()

相关问题