I have a problem. When I use notify() in a synchronized block, I have an IllegalMonitorStateException. Can someone help me solve this problem?
I have to do this, one thread will send a char to the second thread, then this thread should wait, and the second thread will print this char. After this second thread, wait and send the next char again first
Main.java:
import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; 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(); } }
source share