Java 如何在JFrame中运行2个线程
嗨,我有以下问题。。。 我的主框架是这样开始的:Java 如何在JFrame中运行2个线程,java,swing,concurrency,event-dispatch-thread,thread-sleep,Java,Swing,Concurrency,Event Dispatch Thread,Thread Sleep,嗨,我有以下问题。。。 我的主框架是这样开始的: public static void main (String args[]){ SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Form3 myF=new Form3(); } }); }; try { whi
public static void main (String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Form3 myF=new Form3();
}
});
};
try {
while (DBAccess.haveResult("ASS"+harnessId)==null&&cancelCycle == 0) {
thread1.sleep(3*1000);
System.out.println("+++++++++");
System.out.println(DBAccess.haveResult("ASS"+harnessId));
res = DBAccess.haveResult("ASS"+harnessId);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
在jframe中,我有JPanel。在jpanel上,我想开始第二个线程。
我这样试过:
public static void main (String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Form3 myF=new Form3();
}
});
};
try {
while (DBAccess.haveResult("ASS"+harnessId)==null&&cancelCycle == 0) {
thread1.sleep(3*1000);
System.out.println("+++++++++");
System.out.println(DBAccess.haveResult("ASS"+harnessId));
res = DBAccess.haveResult("ASS"+harnessId);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
但我无法停止该线程,甚至无法取消它,因为主窗口停止反应
为了澄清我的问题:
我在JPanel上有“Test”按钮,它正在启动测试过程。测试过程由每3秒重复一次的循环组成,该循环检查数据库状态。问题是在状态显示为db(while条件)之前,我无法停止此循环,因为在我单击“测试”后窗口正忙。即使实现runnable并将测试方法放入“run()”也不起作用
testbutton源代码:
if (e.getActionCommand().equals("Test")){
run();}
运行方法:
@Override
public final void run() {
test();
}
试验方法:
Map result_row = DBAccess.addRow("ASS"+harnessId,htOperList.get(seqNumber-1).getNametestprogram(),"",null);
if(result_row.containsKey("ADDROW")){System.out.println("Record inserted" );}
Database db = null;
Map res = null;
try {
while (DBAccess.haveResult("ASS"+harnessId)==null&&cancelCycle == 0) {
thread1.sleep(3*1000);
System.out.println(DBAccess.haveResult("ASS"+harnessId));
res = DBAccess.haveResult("ASS"+harnessId);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
您正在阻止事件分派线程。在繁重的任务中使用一种新的方法。将主数据库操作置于
doInBackround()
中,并使用publish()
获得中间结果
如果需要在
doInBackround()
完成之前停止,可以使用cancel()
。请参阅,以获取有关此操作的说明。您正在阻止事件调度线程。在繁重的任务中使用一种新的方法。将主数据库操作置于doInBackround()
中,并使用publish()
获得中间结果
如果需要在
doInBackround()
完成之前停止,可以使用cancel()
。请参阅以获取有关注意事项。如果窗口停止反应,则表示循环不会在单独的线程中运行,而是在事件分派线程中运行,这会导致UI冻结。向我们展示如何声明、初始化和启动线程。添加了更多源代码通过调用Runnable的run()
方法,您不会启动线程。这只是调用当前线程中的方法。阅读。@Michael:请看一看,这可能会给你一个关于如何做到这一点的模糊想法,尽管如回答中所述,SwingWorker
要好得多,因为程序员不必担心GUI相关的更新,因为如果窗口停止反应,它们会自动在EDT
:-)上执行,这意味着循环不会在单独的线程中运行,而是在事件分派线程中运行,这会导致UI冻结。向我们展示如何声明、初始化和启动线程。添加了更多源代码通过调用Runnable的run()
方法,您不会启动线程。这只是调用当前线程中的方法。阅读。@Michael:请看一看,这可能会给你一个关于如何做到这一点的模糊想法,尽管如回答中所述,SwingWorker
要好得多,因为程序员不必担心GUI相关的更新,因为它们是在EDT
:-)上自动执行的