好处:
底层都是ThreadPoolExecutor
Executors.newFixedThreadPool
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池5个处理线程
try {
for (int i = 0; i < 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName()+"办理业务");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
pool-1-thread-2办理业务
pool-1-thread-3办理业务
pool-1-thread-1办理业务
pool-1-thread-5办理业务
pool-1-thread-3办理业务
pool-1-thread-2办理业务
pool-1-thread-3办理业务
pool-1-thread-4办理业务
pool-1-thread-5办理业务
pool-1-thread-1办理业务
Executors.newSingleThreadExecutor()
ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池一线程
try {
for (int i = 0; i < 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName()+"办理业务");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
只有一个线程处理
Executors.newCachedThreadPool()
ExecutorService threadPool = Executors.newCachedThreadPool();//一池N线程 动态调整线程数
try {
for (int i = 0; i < 100; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName()+"办理业务");
});
TimeUnit.MILLISECONDS.sleep(200);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
pool-1-thread-1办理业务
去掉 TimeUnit.MILLISECONDS.sleep(200);
pool-1-thread-1办理业务
pool-1-thread-5办理业务
pool-1-thread-6办理业务
pool-1-thread-4办理业务
pool-1-thread-3办理业务
pool-1-thread-8办理业务
pool-1-thread-2办理业务
pool-1-thread-7办理业务
pool-1-thread-9办理业务
pool-1-thread-3办理业务
pool-1-thread-1办理业务
多个线程调用