2012-03-05 72 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