有时候并不是在任何场景下使用线程池,效率都比顺序执行程序快,请看下面例子程序:
这是使用线程池程序。
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
KEEP_ALIVE_TIME, TimeUnit.SECONDS, nocardTaskQueue);
threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
long threadStartTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Future future = threadPool.submit(new TestRunnable());
try {
future.get(1000, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
long threadEndTime = System.currentTimeMillis();
System.out.println("采用线程池处理:" + (threadEndTime - threadStartTime));
这是顺序执行程序:
long objectStartTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
TestRunnable tt = new TestRunnable();
tt.run();
}
long objectEndTime = System.currentTimeMillis();
System.out.println("采用普通类处理:" + (objectEndTime - objectStartTime));
执行结果是: