您好,我遇到了以下问题... 我的主 jframe 是这样启动的:
public static void main (String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Form3 myF=new Form3();
}
});
};
在 jframe 中我有 Jpanels。在 jpanel 上,我想启动第二个线程。 我这样试过:
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();
}
但我无法停止该线程,甚至无法取消它,因为主窗口停止 react
澄清我的问题: 我在 JPanel 上有“测试”按钮,它正在开始测试过程。测试过程由每 3 秒重复一次的循环组成,该循环检查数据库状态。问题是我无法停止此循环,直到状态出现在 db 中(while 条件),因为在我单击“测试”后窗口正忙。即使实现 runnable 并将测试方法放入“run()”也没有用。
测试按钮源代码:
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();
}
最佳答案
您正在阻塞事件分发线程。使用SwingWorker对于繁重的任务。将主要的 DB 操作放在 doInBackround()
中,并使用 publish()
获取中间结果。
如果您需要在 doInBackround()
完成之前停止它,您可以使用 cancel()
。参见 here有关的注释。
关于java - JFrame中如何运行2个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18334200/