小编skk*_*skk的帖子

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

在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)

java swing multithreading

5
推荐指数
2
解决办法
1583
查看次数

标签 统计

java ×1

multithreading ×1

swing ×1