在一個swing應用程序中,我想重新利用一個派生線程,而不是創建一個新的服務請求。這是因爲請求會在很短的時間間隔內完成,並且爲每個請求創建新線程的成本可能很高。使用sleep()和interrupt()來重用線程
我想使用中斷()和睡眠()方法如下做到這一點的,想知道的代碼的任何潛在的性能問題:
public class MyUtils {
private static TabSwitcherThread tabSwitcherThread = null;
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
tabSwitcherThread = new TabSwitcherThread();
tabSwitcherThread.start();
}
else
tabSwitcherThread.interrupt();
}
private static class TabSwitcherThread extends Thread{
@Override
public void run() {
try {
//Serve request code
//Processing complete, sleep till next request is received (will be interrupted)
Thread.sleep(60000);
} catch (InterruptedException e) {
//Interrupted execute request
run();
}
//No request received till sleep completed so let the thread die
}
}
}
感謝
實際上,我認爲你是TabSwitcherThread會得到計算器例外早晚,因爲你有你的run()方法遞歸調用:) – Alvin 2011-05-28 09:38:19