使用ExecutorService,而不是执行Thread.start

Paw*_*wan 4 java multithreading executorservice

我正在研究现有的代码,我在其中一个类中找到了这段代码.代码正在使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 5

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

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

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