我想了解使用線程池的優勢,我寫了這段代碼來查看固定線程池的時間改進。線程池性能
首先,我將池中的線程數設置爲1,大約需要920 ms,然後我將池中的線程數更改爲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);
}
}
}
}
而不是10個任務,嘗試提交100000個任務。並且不要讓它們打印到'System.out'中,因爲它會同步(所以一次只能打印一個線程,否定線程的任何優點)。 – immibis 2014-09-27 11:55:51
@immibis這裏的關鍵確實是'System.out.println()'調用的同步。這一點以及並行處理不會提升任何I/O綁定進程的事實。 – biziclop 2014-09-27 12:06:08