【发布时间】:2025-11-28 20:10:01
【问题描述】:
我正在用java写一个简单的多线程练习。我需要做的基本上就是制作一个带有两个按钮(“开始”和“结束”)的 JFrame。如果用户点击“开始”按钮,控制台将开始打印出“正在打印”。如果单击“结束”,控制台将停止打印。再次单击“开始”将恢复打印。
这是我的代码(不相关的部分没有显示):
//import not shown
public class Example extends JFrame implements Runnable {
private static boolean print, started;//print tells whether the thread should keep printing
//things out, started tells whether the thread has been
//started
private JButton start;//start button
private JButton end;//end button
private static Thread thr;//the thread that is going to do the printing
//other fields not shown
public Example(String title) {
Container c = getContentPane();
//set up the JFrame
//...parts not shown
start = new JButton("Start");
end = new JButton("End");
c.add(start);
c.add(end);
//add the actionListner for the buttons
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (started == false) {
thr.start();// if the thread has not been started, start the thread
started = true;
}else{//otherwise waken the thread. This is to prevent IllegalThreadStateException.
thr.notify();
}
print = true;//should print things out
}
});
end.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(started) {//This action won't pause the thread if its not yet started
try {
thr.wait();//pause the thread
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
print = false;//should stop printing
}
});
validate();
setVisible(true);
}
@Override
public void run() {//override run() method
while (print) {
System.out.println("Printing");//print out "Printing"
}
}
public static void main(String[] args) {//main method
Example ex = new Example("My Frame");//instantiate the frame
thr = new Thread(ex);//make a new thread;
started = false;//the thread has not been started, so set started to false;
}
}
但是,一旦单击开始按钮,控制台就不会停止打印。我不断收到 IllegalMonitorStateException。是什么导致了这个问题? 我找不到错误,因为所有部分似乎在逻辑上都是正确的。任何帮助将不胜感激。
【问题讨论】:
-
我认为 thr.wait() 和 thr.notify() 是问题所在。但是如果我不使用它们,我用什么来暂停和恢复线程呢?
-
wait()不会像您认为的那样做。提示:它继承自 Object,并且有一个不错的 javadoc ... -
IllegalMonitorStateException - 如果当前线程不是对象监视器的所有者这是我不断得到的。
标签: java multithreading swing