1
運行2個線程
嗨,我得到了下面的問題...... 我有主JFrame的開始是這樣的。在jpanel上,我想開始第二個線程。 我試着這樣說:如何在JFrame中
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,它正在開始測試過程。測試過程由循環組成,每3秒重複一次,此循環檢查數據庫狀態。問題是我無法停止這個循環,直到狀態出現在db(while condition)中,因爲在點擊「test」後窗口很忙。即使實現runnable並將測試方法放入「run()」也不起作用。
testbutton源代碼:
if (e.getActionCommand().equals("Test")){
run();}
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();
}
如果窗口停止反應,這意味着循環不會在單獨的線程中運行,而是在導致UI凍結的事件調度線程中運行。告訴我們你如何聲明,初始化和啓動你的線程。 –
添加了更多源代碼 – Michael
您不需要通過調用Runnable的run()方法來啓動線程。這只是調用當前線程中的方法。閱讀[併發教程](http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html)。 –