2014-12-08 67 views
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); 
      } 
     } 
    } 
} 
+1

你想實現什麼? – 2014-12-08 07:39:04

+0

看看這個StackOverflow的問題:[IllegalMonitorStateException在等待()調用](http://stackoverflow.com/questions/1537116/illegalmonitorstateexception-on-wait-call) – 2014-12-08 07:50:19

+0

我不能把睡眠,因爲它不允許我打印它按順序。 我想寫一個單一的運行,將被兩個線程訪問,一個會打印,甚至會打印奇數(按順序)。 – 2014-12-08 08:47:46

回答

0

要暫停線程,您需要使用Thread.sleep()而不是wait()