【发布时间】:2012-10-31 07:34:24
【问题描述】:
我正在尝试学习如何在 java 中暂停和恢复线程。我正在使用Applet,implements Runnable 有 2 个按钮“开始”和“停止”。
public void init(){
th = new Thread(this);
th.start();
btn_increment = new Button("Start");
btn_increment.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
th.notify();
}
});
add(btn_increment);
btn_decrement = new Button("Stop");
btn_decrement.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
try{
th.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
});
add(btn_decrement);
}
线程的run方法:
public void run(){
while(true){
repaint();
try{
Thread.sleep(20);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
现在每当我尝试暂停或恢复线程时,都会引发异常:
Exception in thread "AWT-EventQueue-1" java.lang.IllegalMonitorStateException
注意事项:
如果我使用不推荐使用的方法suspend() 和resume(),前面的代码可以完美运行,但文档指出使用notify() 和wait() 来代替同步。我尝试在actionPerformed 方法中添加单词synchronized,但它仍然抛出异常。
谁能解释一下为什么这不起作用以及如何解决同步问题?很少有解释点真的会有很大帮助;)
【问题讨论】:
-
我不确定您是否能够在示例中看到
wait()和notify()的效果。为什么不使用更简单的示例而不是使用小程序?至于您的问题,它不起作用,因为要调用wait()或notify(),您必须拥有要调用该方法的对象的锁。
标签: java multithreading applet synchronization synchronized