2013-04-20 23 views
2

我說的是Thread實例,如果他們獲得Runnable作爲構造函數參數提供,並且只能執行它們的start方法一次,那麼Executor*類系列如何重用它們? PS:我知道並使用比裸線更好抽象的Executors類,我只是出於好奇而問這個問題。java.util.concurrent類如何重用線程?

回答

4

傳遞給執行程序線程的runnables(讓我們稱它們爲R)事實上被包裝在其他runnables(讓我們稱之爲W)中。 W的run()方法的僞代碼是

while (threadMustRun) { 
    wait for new R to be submitted and assigned to this thread 
    execute R.run() 
} 

它實際上比這更復雜,但您應該明白。要真正理解它的作用,請查看代碼ThreadPoolExecutor.Worker內部類。