2015-02-10 89 views
0

我有一個應用程序有3個線程,我將切換到由ScheduledExecutorService進行管理。當創建這個實例時,你必須指定線程池的大小,但是這是什麼?這是否意味着如果我計劃運行3個任務,我應該爲每個任務創建一個3個線程池大小?Java線程池大小(Executors)

+0

一個很好的文章你是如何創建一個ScheduledExecutorService的? – 2015-02-10 12:21:31

+0

ScheduledExecutorService executor = Executors.newScheduledThreadPool(3); executor.scheduleAtFixedRate(task1,0,period,TimeUnit.MILLISECONDS); – user3469157 2015-02-10 12:31:17

回答

0

假設你已經創建ScheduledExecutorService的這樣

ScheduledExecutorService executorService = Executors.newFixedThreadPool(10); 

executorService.execute(new Runnable() { 
    public void run() { 
     System.out.println("Asynchronous task"); 
    } 
}); 

executorService.shutdown(); 

現在這裏發生了什麼:使用newFixedThreadPool() 工廠方法創建

  • 首先一個ExecutorService。這將創建一個線程池,並執行任務10 threads
  • 其次,傳遞給execute()方法的Runnable接口的匿名實現是 。這會導致Runnable由ExecutorService中的一個線程執行爲 。

線程池管理工作者線程池。 thread pools包含一個工作隊列,其中包含等待執行的任務。

現在來到:

這是否意味着,如果我打算上運行3個任務我應該創建一個3每個的 線程池的大小?

是的,以便所有3個任務可以並行執行。

現在這裏是約How big should our thread pool be?

+0

非常感謝! – user3469157 2015-02-10 13:59:10