Mic*_*ael 1 java concurrency swing event-dispatch-thread thread-sleep
嗨我有以下问题...我有这样的主jframe开始:
public static void main (String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Form3 myF=new Form3();
}
});
};
Run Code Online (Sandbox Code Playgroud)
在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();
}
Run Code Online (Sandbox Code Playgroud)
但是我无法阻止那个线程,甚至无法取消它,因为主窗口停止反应
澄清我的问题:我在JPanel上有"测试"按钮,它正在启动测试过程.测试过程包括循环,每3秒重复一次,此循环检查数据库状态.问题是我无法停止此循环,直到状态出现在db(条件)中,因为我点击"test"后窗口很忙.即使实现runnable并将测试方法放入"run()"也无效.
testbutton源代码:
if (e.getActionCommand().equals("Test")){
run();}
Run Code Online (Sandbox Code Playgroud)
运行方法:
@Override
public final void run() {
test();
}
Run Code Online (Sandbox Code Playgroud)
测试方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
您正在阻止事件派发线程.使用SwingWorker执行繁重的任务.将主DB操作放入doInBackround(),并publish()用于中间结果.
如果您需要在doInBackround()完成之前停止它,您可以使用cancel().请参阅此处了解相关说明.