Java 使用sleep()和interrupt()重用线程
在swing应用程序中,我希望重新利用生成的线程,而不是创建一个新线程来服务请求。这是因为请求的时间间隔很短,为每个请求创建新线程的成本可能很高 我正在考虑使用interrupt()和sleep()方法来完成以下任务,并希望了解代码中的任何潜在性能问题:Java 使用sleep()和interrupt()重用线程,java,multithreading,swing,Java,Multithreading,Swing,在swing应用程序中,我希望重新利用生成的线程,而不是创建一个新线程来服务请求。这是因为请求的时间间隔很短,为每个请求创建新线程的成本可能很高 我正在考虑使用interrupt()和sleep()方法来完成以下任务,并希望了解代码中的任何潜在性能问题: public class MyUtils { private static TabSwitcherThread tabSwitcherThread = null; public static void handleStateC
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
}
}
}
谢谢我不会使用sleep()
和interrupt()
-如果我必须的话,我会使用wait()
和notify()
但是,是否真的需要这样做,而不是使用ThreadPoolExecutor
,它可以为您处理线程重用?或者以生产者/消费者的方式使用阻塞队列
Java已经为此提供了足够多的高级构建块,您不需要亲自进入这个级别。我认为您需要的是一个线程池。Java5及以上版本随附。我建议您使用Java提供的工具,而不是编写自己的工具,这样可以节省大量的时间和精力 当然,如果你必须按照你描述的方式去做(嘿,有时候业务需求会让我们的生活变得艰难),那么按照Jon的建议使用wait()和notify()。在这种情况下,我不会使用sleep(),因为您必须指定超时时间,而且您永远不知道下一个请求何时到达。对于我来说,拥有一个不断醒来然后又回到睡眠状态的线程似乎有点浪费CPU周期 下面是一个关于ThreadPoolExecutor的示例 编辑: 下面是一些代码示例:
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.
}
}
}
谢谢你的回复。这是一个小型java应用程序,我不想让“n”个线程池来服务请求。基本上,每次都会有一个请求。这种情况就像在文本区域中,用户键入一些内容,这需要进行处理。我不能在同一个线程中执行它,因为它会导致UI冻结,因此需要一个单独的thead。为此,我希望有一个专用线程,并避免创建新线程,因为我在创建新线程时经历了相当大的延迟。谢谢@skk一个线程池有什么问题?:)。我用一个示例代码修改了我的答案,说明了如何利用Java并发框架。我借用了你的部分代码,希望你不会介意。@skk:生产者/消费者队列可以帮你,或者一个带有一个线程的
ThreadPoolExecutor
。Jon和Alvin看了一下API,是的,带有一个线程的ThreadPoolExecutor适合我的需要。非常感谢@JonSkeet,选择等待/通知而不是睡眠/中断的原因是什么?虽然wait()
确实不需要特定的超时,但我们有睡眠(长毫秒)
,其最大值约为~3亿年,本质上类似于wait()
。事实上,我认为睡眠/中断性能更高,因为它不需要进行冗余同步(它只是直接完成任务)。我对您对这个问题的想法很感兴趣。实际上,我认为您是TabSwitcherThread迟早会出现stackoverflow异常,因为您的run()方法中有递归调用:)