在swing应用程序中,我希望重用一个派生的线程,而不是创建一个新的线程来服务请求。这是因为请求会以很短的时间间隔到来,并且为每个请求创建新线程的成本可能很高。
我正在考虑使用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
}
}
}谢谢
发布于 2011-05-28 17:17:40
我想你要找的是一个ThreadPool。Java5及更高版本附带了ThreadPoolExecutor。我建议您使用Java提供的内容,而不是编写自己的代码,这样可以节省大量的时间和精力。
当然,如果你一定要按照你所描述的方式去做(嘿,有时候业务需求会让我们的生活变得很艰难),那么就像Jon建议的那样使用wait()和notify()。在这种情况下,我不会使用sleep(),因为您必须指定超时,并且您永远不知道下一个请求何时会进入。让一个线程保持唤醒,然后再进入睡眠,这对我来说似乎有点浪费CPU周期。
这是一个关于ThreadPoolExecutor的nice tutorial。
编辑:
下面是一些代码示例:
public class MyUtils {
private static UIUpdater worker = null;
private static ExecutorService exeSrv = Executors.newFixedThreadPool(1);
public static void handleStateChange(){
if(tabSwitcherThread == null || !tabSwitcherThread.isAlive()){
worker = new UIUpdater();
}
//this call does not block
exeSrv.submit(worker, new Object());
}
private static class UIUpdater implements Runnable{
@Override
public void run() {
//do server request and update ui.
}
}
}发布于 2011-05-28 17:13:05
我不会使用sleep()和interrupt() --如果必要的话,我会使用wait()和notify()。
但是,是否真的需要这样做,而不是使用可以为您处理线程重用的ThreadPoolExecutor呢?或者以生产者/消费者的方式使用BlockingQueue?
Java已经为此提供了足够的更高级别的构建块,您不应该自己深入到这个级别。
https://stackoverflow.com/questions/6160681
复制相似问题