我正在使用Java中的应用程序来更新每秒的结果,直到它停止。在30秒钟内,它会每秒调用一组特定的方法,然后在接下来的30秒内调用另一组方法,然后再次调用第一组,然后依此类推。由于我希望能够在任何时候停止并重新启动在后台执行的计算,因此我创建了一个GUI和几个按钮来启动和停止新线程,以及一种显示结果的方法每一秒。Java线程问题
我遇到的问题是,一旦新线程启动,我不能切换回GUI,直到它完成,并且由于线程将继续前进,直到我告诉它停止,我最终不能退出无限循环。我可以通过将GUI放在它自己的线程中来解决这个问题,以便两个线程同时运行?如果是这样,我将如何从GUI内部做到这一点?
我正在使用多个类,所以我不想发布不相关的东西。
public class GUI extends javax.swing.JFrame implements Runnable{
Graphics g;
Threads thread = new Threads();
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
thread.run()
}
[..]
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
thread.stop()
}
}
public class Threads implements Runnable{
boolean opened=false;
road first = new road();
public void run() {
opened=true;
first.standardInitialization();
while(opened){
for(int i=0; i<30 && opened; i++){
try {
first.redLightAction();
System.out.println("cars: " + first.firstLight.cars);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Threads.class.getName()).log(Level.SEVERE, null, ex);
}
}
for(int i=0; i<30 && opened; i++){
try {
first.greenLightAction();
second.greenLightAction();
System.out.println("cars: " + first.firstLight.cars);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Threads.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void stop(){
opened=false;
}
}
请发表相关的代码。 – MByD 2011-04-15 21:44:00
邮政编码。如果确实创建了一个新线程来执行该工作,它不应该影响GUI线程。 – 2011-04-15 21:44:15
这篇文章将回答您的问题,并为您提供可帮助您的解决方案:[并发性](http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html) – 2011-04-15 21:46:24