看一個Demo:
public class ThreadPool {
public static void main(String[] args) {
threadDemo(100000);
poolDemo(100000);
}
public static void poolDemo(int count) {
long startTime = System.currentTimeMillis();
final List<Integer> l = new LinkedList<>();
ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count));
final Random random = new Random();
for (int i = 0; i < count; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
l.add(random.nextInt());
}
};
tp.execute(runnable);
}
tp.shutdown();
try {
tp.awaitTermination(1, TimeUnit.DAYS);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadPool spend time:" + (System.currentTimeMillis() - startTime));
System.out.println(l.size());
}
public static void threadDemo(int count) {
long startTime = System.currentTimeMillis();
final List<Integer> l = new LinkedList<>();
final Random random = new Random();
for (int i = 0; i < count; i++) {
Thread thread = new Thread(() -> l.add(random.nextInt()));
thread.start();
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread spend time:"+(System.currentTimeMillis() - startTime));
System.out.println(l.size());
}
}
上面這個Demo分別用線程的方法和線程池的方法創(chuàng)建了100000個隨機數(shù),運行后控制臺的輸出結(jié)果是這樣的:
Thread spend time:11840
100000
ThreadPool spend time:37
100000
Process finished with exit code 0
可以看到使用線程池的方法節(jié)省了大量的時間,而單線程多出來的時間主要就是花在了線程的創(chuàng)建上他宛。
線程池的作用就是限制程序中執(zhí)行線程的數(shù)量,使用線程池可以減少線程被創(chuàng)建和被銷毀的次數(shù)卿吐,每個線程都能重復使用富弦,可以節(jié)省系統(tǒng)資源,提高程序的運行效率壹罚。