使用 ExecutorService ,而不是执行 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扩展ThreadThread实现Runnable.您在该代码中所做的是将 Runnable 提交给执行器,执行器将在其 25 个线程之一中执行它。

这与直接使用 myThread.start() 启动线程之间的主要区别在于,如果您有 10k 行,这可能会同时启动 10k 个线程,这可能会很快耗尽您的资源。

按照所定义的执行器,任何时候运行的线程都不会超过 25 个,因此,如果在所有 25 个线程已在使用的情况下提交任务,它将等到其中一个线程再次可用并在该线程中运行。

最新更新