2012-03-05 58 views
0

我有2个以下的类。不同的客户拨打TestThreadPool,然后拨打TestThreadExecutor访问ExecutorService。所以问题是,ThreadPool永远不会被启动,因为它总是会创建一个新的TestThreadExecutorstatic ExecutorService

所以,我想设置executeThreadExecutor作为静态方法来启动threadPool。有静态方法和静态ExecutorService有什么问题吗?

像单身人士等有其他的替代方法吗?


public class Client { 
    ... 
    TestThreadPool testThreadPool = new TestThreadPool(); 
    ... 
} 

public class TestThreadPool { 
    public void executeThread() { 
    TestThreadExecutor test = new TestThreadExecutor(); 
    ... 
    } 
} 

public class TestThreadExecutor { 
    public static ExecutorService testService = null; 

    public static void executeThreadExecutor { 
    if (testService == null) {  
     testService = Executors.newFixedThreadPool(15); 
    } 
    ... 
    } 
} 

回答

0

你的做法似乎确定,并没有与它没有任何问题,但我看不出有任何理由让公众ExecutorService,因为你是通过类的方法管理它,这封装效果更好。当然,你可以实现TestThreadExecutor作为一个单身人士:

public class TestThreadExecutor { 
    private ExecutorService testService = Executors.newFixedThreadPool(15); 
    private static TestThreadExecutor instance = new TestThreadExecutor(); 

    private TestThreadExecutor() { 
    } 

    public static TestThreadExecutor getInstance() { 
     return instance; 
    }   
} 
+1

你为什么要在构造函数中设置testService?为什么不直接设置它?在类构造函数中设置静态变量会让人困惑。 – jtahlborn 2012-03-05 16:30:53

+0

@jtahlborn:我同意,现在我想起来了,这有点令人困惑。 – Tudor 2012-03-05 16:36:42

+0

谢谢。这对我很有帮助。我想把executorService.shutdown()。我应该在哪里?它在catch块吗?我试着把它放进去,它不接受新的任务。 – user12121 2012-03-05 23:13:40