public static void main(String[] args) { //创建固定线程池,生产环境不用,会发生OOM ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2); try { for (int i = 1; i <=6; i++) { int finalI = i; fixedThreadPool.execute(() -> { System.out.println("线程名称:" + Thread.currentThread().getName() + ",固定数量:" + finalI); }); } } finally { fixedThreadPool.shutdown(); } //创建单个线程池,生产环境不用,会发生OOM ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); try { for (int i = 1; i <= 6; i++) { int finalI = i; singleThreadExecutor.execute(() -> { System.out.println("线程名称:" + Thread.currentThread().getName() + ",单个线程:" + finalI); }); } } finally { fixedThreadPool.shutdown(); } //创建动态线程池,生产环境不用,会发生OOM ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); try { for (int i = 1; i <= 6; i++) { int finalI = i; cachedThreadPool.execute(() -> { System.out.println("线程名称:" + Thread.currentThread().getName() + ",动态线程:" + finalI); }); } } finally { fixedThreadPool.shutdown(); } }
线程名称:pool-1-thread-1,固定数量:1 线程名称:pool-1-thread-2,固定数量:2 线程名称:pool-1-thread-1,固定数量:3 线程名称:pool-1-thread-2,固定数量:4 线程名称:pool-1-thread-1,固定数量:5 线程名称:pool-1-thread-2,固定数量:6 线程名称:pool-2-thread-1,单个线程:1 线程名称:pool-2-thread-1,单个线程:2 线程名称:pool-2-thread-1,单个线程:3 线程名称:pool-2-thread-1,单个线程:4 线程名称:pool-2-thread-1,单个线程:5 线程名称:pool-2-thread-1,单个线程:6 线程名称:pool-3-thread-1,动态线程:1 线程名称:pool-3-thread-2,动态线程:2 线程名称:pool-3-thread-4,动态线程:4 线程名称:pool-3-thread-3,动态线程:3 线程名称:pool-3-thread-5,动态线程:5 线程名称:pool-3-thread-6,动态线程:6