2013-01-09 43 views
4

我有一個問題。當我在同步塊中使用notify()時,我有IllegalMonitorStateException。任何人都可以幫我解決這個問題嗎?IllegalMonitorStateException notify()和wait()

我必須這樣做,一個線程將發送到第二個線程字符,然後此線程必須等待,第二個線程打印此字符。這第二個線程等待,第一個後再次發送下一個字符

Main.java:

import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
public class Main extends JFrame { 

    Thread t1, t2; 
    Consumer con; 

    public Main() { 
     con = new Consumer(); 
     startThreads(); 
    } 

    private synchronized void startThreads() { 
     t1 = new Thread(new Producent("grudzien", con)); 
     t1.start(); 
     t2 = new Thread(con); 
     t2.start(); 
    } 

    public class Producent implements Runnable { 

     String m_atom; 
     char[] atoms; 
     Consumer m_c; 

     public Producent(String atom, Consumer c) { 
      m_atom = atom; 
      m_c = c; 
     } 

     @Override 
     public void run() { 
      synchronized (this) { 
       atoms = m_atom.toCharArray(); 
       System.out.print("Tablica znaków: "); 
       for (int i = 0; i < atoms.length; i++) { 
        System.out.print(atoms[i] + ", "); 
       } 
      } 
      for (int i = 0; i < atoms.length; i++) { 
       synchronized (this) { 
        con.setChar(atoms[i]); 
        t2.notify(); 
        try { 
         wait(); 
        } catch (InterruptedException ex) { 
         JOptionPane.showMessageDialog(null, "Blad w wait()", "Blad!", JOptionPane.ERROR_MESSAGE); 
        } 
       } 
      } 

     } 
    } 

    public class Consumer implements Runnable { 

     char atom; 

     public void setChar(char c) { 
      atom = c; 
     } 

     @Override 
     public void run() { 
      while (true) { 
       synchronized (this) { 
        try { 
         wait(); 
        } catch (InterruptedException ex) { 
         JOptionPane.showMessageDialog(null, "Blad w wait()", "Blad!", JOptionPane.ERROR_MESSAGE); 
        } 
        System.out.println(atom); 
        t1.notify(); 
       } 
      } 
     } 
    } 

    public static void main(String[] args) { 
     new Main(); 
    } 
} 
+1

你能包括實際的例外嗎? – radai

+0

異常在線程 「線程2」 java.lang.IllegalMonitorStateException \t在java.lang.Object.notify(本機方法) \t在主$ Producent.run(Main.java:53) \t在java.lang中。 Thread.run(Thread.java:662) – Sylwek

+0

可能的重複http://stackoverflow.com/q/886722/413032 –

回答

7

你需要的是能打電話通知它的「對象監視器的所有者」。到目前爲止你的方法都是synchronized(this),但他們調用其他對象的notify()(它們不同步)。換句話說:

synchronized(t2) { 
    t2.notify(); 
} 

synchronized(t1) { 
    t1.notify(); 
} 

在Java監控和同步的完整說明,請參見here,或者尋找類似的問題在這裏SO,像這樣的 - Java Wait and Notify: IllegalMonitorStateException

相關問題