我正在尝试理解使用线程池的优势,我编写了这段代码来查看使用固定线程池的时间改进。首先,我将线程池中的线程数设置为1,大约需要920毫秒,然后我将线程池中的线程数更改为2(和3,4,5,6,7...),需要1200毫秒,当线程同时运行时难道不应该更快吗?当我将其更改为缓存线程池时,也需要1200毫秒。
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Example3 {
public static void main(String[] args) {
new Example3();
}
public Example3() {
try {
testFixedPool(1);
//testFixedPool(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void testFixedPool(int numberOfThreads) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
executor.execute(new TaskPrintInteger(0, 10000));
executor.execute(new TaskPrintInteger(1, 10000));
executor.execute(new TaskPrintInteger(2, 10000));
executor.execute(new TaskPrintInteger(3, 10000));
executor.execute(new TaskPrintInteger(4, 10000));
executor.execute(new TaskPrintInteger(5, 10000));
executor.execute(new TaskPrintInteger(6, 10000));
executor.execute(new TaskPrintInteger(7, 10000));
executor.execute(new TaskPrintInteger(8, 10000));
executor.execute(new TaskPrintInteger(9, 10000));
executor.shutdown();
while(!executor.isTerminated()){
}
System.out.println();
System.out.println((System.currentTimeMillis()) - start);
}
private class TaskPrintInteger implements Runnable {
private int number, times;
public TaskPrintInteger(int number, int times) {
this.number = number;
this.times = times;
}
@Override
public void run() {
for (int i = 0; i < times; i++) {
System.out.println(number);
}
}
}
}
System.out
,因为这会同步化(所以只有一个线程在打印,抵消了任何线程优势)。 - user253751System.out.println()
调用的同步。并且并行处理不会提高任何 I/O 绑定的进程。 - biziclop