我正在处理现有代码,我在其中一个类中找到了这段代码。
代码使用的是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);
}
}
答案 0 :(得分:5)
我认为MyThread
扩展Thread
和Thread
实现Runnable
。你在该代码中所做的是向执行程序提交一个Runnable,它将在25个线程中的一个中执行它。
直接用myThread.start()
启动线程的主要区别在于,如果你有10k行,这可能会同时启动10k个线程,这可能会很快耗尽你的资源。
对于定义的执行程序,任何时候都不会运行超过25个线程,因此如果在所有25个线程都在使用的情况下提交任务,它将等待其中一个线程再次可用并运行在那个帖子里。