我对在循环中使用线程进行了广泛的搜索,虽然我了解独立线程如何工作的概念,但我似乎仍然无法掌握如何在我的简单应用程序中实现它。
我的应用程序包含一个带有文本框的表单。此文本框需要在每次循环迭代时更新一次。它以按下按钮开始,但循环也应以按下停止按钮结束。我使用了一个 boolean 值来跟踪它是否被按下。
这是我的表单代码:
package threadtester;
public class MainForm extends javax.swing.JFrame {
public MainForm() {
initComponents();
}
private void RunButtonActionPerformed(java.awt.event.ActionEvent evt) {
ThreadTester.setRunnable(true);
ThreadTester example = new ThreadTester(2,this);
example.run();
}
private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {
ThreadTester.setRunnable(false);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
public void setTextBox(String myString){
MainTextbox.setText(myString);
}
}
如您所见,我按下了一个按钮。当按下按钮时,这将执行另一个名为 ThreadTester 的类中的代码。这是该类的代码:
package threadtester;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadTester implements Runnable
{
int thisThread;
MainForm myMainForm;
private static boolean runnable;
// constructor
public ThreadTester (int number,MainForm mainForm)
{
thisThread = number;
myMainForm = mainForm;
}
public void run ()
{
for (int i =0;i< 20; i++) {
if(runnable==false){
break;
}
System.out.println("I'm in thread " + thisThread + " line " + i);
myMainForm.setTextBox(i + "counter");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
}
} }
public static void setRunnable(Boolean myValue){
runnable = myValue;
}
public static void main(String[] args) {
MainForm.main(args);
}
}
如您所见,循环是在单独的线程上创建的...但文本框仅在循环完成后更新。现在据我所知,我在 MainForm 中创建了一个单独的线程来运行循环,所以我不明白为什么它没有运行?任何指导将不胜感激,我尝试查看有关堆栈交换的示例,但我似乎无法让它们适合我的实现。
根据 Tassos 的建议,我的运行方法现在看起来像这样:
public void run ()
{
for (int i =0;i< 20; i++) {
if(runnable==false){
break;
}
System.out.println("I'm in thread " + thisThread + " line " + i);
final String var = i + "counter";
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
myMainForm.setTextBox(var);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
}
} }
最佳答案
为了使 Tassos 的回答生效,您实际上必须创建一个新线程,而您并没有这么做。简单调用
ThreadTester example = new ThreadTester(2,this);
example.run();
还不够,因为只是从 EDT 调用 run
方法。您需要执行以下操作:
Thread t = new Thread(new ThreadTester(2,this));
t.start();
请引用Defining and Starting a Thread .
此外,您还想从两个不同的线程 (runnable
) 修改同一个字段,这是一个错误。您应该阅读有关 Java 并发的更多信息。
关于java - 使用线程循环更新 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17107728/