gpt4 book ai didi

java - IllegalMonitorStateException notify() 和 wait()

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:27 24 4
gpt4 key购买 nike

<分区>

我有一个问题。当我在同步块(synchronized block)中使用 notify() 时,我得到 IllegalMonitorStateException。谁能帮我解决这个问题?

我需要一个线程向第二个线程发送一个字符,然后这个线程必须等待,第二个线程打印这个字符。在第二个线程等待之后,第一个线程再次发送下一个字符

主要.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();
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com