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个线程都已在使用的情况下提交任务,它将等待其中一个线程再次可用并在该线程中运行