使用sleep()和interrupt()重用线程

skk*_*skk 5 java swing multithreading

在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         
        }
   }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Jon*_*eet 10

我不会用sleep()interrupt()-我会用wait()notify(),如果我绝对必须.

但是,有没有真正需要这样做而不是使用ThreadPoolExecutor哪个可以为您处理线程重用?或者也许BlockingQueue以生产者/消费者的方式使用?

Java已经为此提供了足够的更高级别的构建块,您不需要自己降低到这个级别.

  • @skk:生产者/消费者队列会为你做这个,或者是一个带有一个线程的`ThreadPoolExecutor`. (2认同)

Alv*_*vin 4

我认为您正在寻找的是线程池。Java 5 及更高版本附带ThreadPoolExecutor。我建议你使用 Java 提供的东西,而不是自己编写,这样你可以节省大量的时间和精力。

当然,如果您绝对必须按照您所描述的方式执行此操作(嘿,有时业务需求让我们的生活变得困难),那么请按照乔恩的建议使用 wait() 和 notification() 。在这种情况下我不会使用 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.
        }
   }
}
Run Code Online (Sandbox Code Playgroud)