2012-11-29 29 views
4

我正在研究一個現有的代碼,我在其中一個類中找到了這段代碼。 代碼使用ExecutorService,而不是MyThread.start使用ExecutorService,而不是做Thread.start

請告訴我爲什麼要使用ExecutorService而不是Thread.start

protected static ExecutorService executor = Executors.newFixedThreadPool(25); 

while (!reader.isEOF()) { 
    String line = reader.readLine(); 
    lineCount++; 
    if ((lineCount > 1) && (line != null)) { 
     MyThread t = new MyThread(line, lineCount); 
     executor.execute(t); 
    } 
} 

回答

5

我想MyThread延伸ThreadThread工具Runnable。您在該代碼中所做的是向可執行程序提交Runnable,該可執行程序將在其25個線程中的一個線程中執行。

與直接使用myThread.start()直接啓動線程的主要區別是,如果您有10K行,則可能會同時啓動10k個線程,這可能會很快耗盡您的資源。

由於定義了執行程序,任何時候都不會有超過25個線程運行,所以如果一個任務在所有25個線程都被使用的時候被提交,它將一直等到其中一個線程再次變爲可用並且在該線程中運行。

相關問題