Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用ExecutorService,而不是执行Thread.start_Java_Multithreading_Executorservice - Fatal编程技术网

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

Java 使用ExecutorService,而不是执行Thread.start,java,multithreading,executorservice,Java,Multithreading,Executorservice,我正在处理一个现有的代码,在其中一个类中发现了这段代码。 代码正在使用ExecutorService,而不是执行MyThread.start protected static ExecutorService executor = Executors.newFixedThreadPool(25); while (!reader.isEOF()) { String line = reader.readLine(); lineCount++; if ((lineCount &

我正在处理一个现有的代码,在其中一个类中发现了这段代码。 代码正在使用
ExecutorService
,而不是执行
MyThread.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);
    }
}
请告诉我为什么要使用
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
。您在该代码中所做的是向executor提交一个Runnable,executor将在其25个线程中的一个线程中执行它

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

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