【发布时间】:2011-05-28 09:07:43
【问题描述】:
在一个摇摆应用程序中,我想重新利用一个衍生线程而不是创建一个新线程来服务请求。这是因为请求会在很短的时间间隔内到来,并且为每个请求创建新线程的成本可能很高。
我正在考虑使用 interrupt() 和 sleep() 方法来执行此操作,如下所示,并想知道代码的任何潜在性能问题:
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 迟早会得到 stackoverflow 异常,因为你的 run() 方法中有递归调用:)
标签: java multithreading swing