[英]Using ExecutorService , instead of doing Thread.start
我正在研究現有的代碼,我在其中一個類中找到了這段代碼。 代碼使用的是ExecutorService
,而不是使用MyThread.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);
}
}
我想MyThread
擴展了Thread
和Thread
實現了Runnable
。 您在該代碼中所做的是向執行程序提交Runnable,它將在其25個線程中的一個中執行它。
直接用myThread.start()
啟動線程的主要區別在於,如果你有10k行,這可能會同時啟動10k個線程,這可能會很快耗盡你的資源。
使用定義的執行程序,任何時候都不會運行超過25個線程,因此如果在所有25個線程都在使用的情況下提交任務,它將等待其中一個線程再次可用並在該線程中運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.