【问题标题】:Using ExecutorService , instead of doing Thread.start使用 ExecutorService ,而不是做 Thread.start
【发布时间】:2012-11-29 18:50:05
【问题描述】:

我正在处理现有代码,我在其中一个类中找到了这段代码。 该代码使用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);
    }
}

【问题讨论】:

    标签: java multithreading executorservice


    【解决方案1】:

    我想MyThread 扩展了ThreadThread 实现Runnable。您在该代码中所做的是将 Runnable 提交给执行程序,执行程序将在其 25 个线程之一中执行它。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-20
      • 2011-06-22
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      相关资源
      最近更新 更多