目录
2.使用 ThreadPoolExecutor 类手动创建线程池:
3.使用 ScheduledThreadPoolExecutor 类创建定时任务线程池:
Java 标准库线程池的创建方式总共有三种:
1. 使用 Executors 类中的静态方法创建线程池;
2. 使用 ThreadPoolExecutor 类手动创建线程池;
3. 使用 ScheduledThreadPoolExecutor 类创建定时任务线程池。
以下是分别使用代码创建并演示这三种方式:
-
使用 Executors 类中的静态方法创建线程池:
ExecutorService service = Executors.newFixedThreadPool(5); service.submit(() ->{ System.out.println("Hello from thread pool"); }); service.shutdown(); }
当我们使用线程池完成任务后,需要调用executor.shutdown()
方法来关闭线程池。这样可以确保线程池不再接受新的任务,并且会等待已经提交的任务执行完成后关闭线程池。可以优雅地关闭线程池,释放资源并防止内存泄漏。这是非常需要注意的!!!
2.使用 ThreadPoolExecutor 类手动创建线程池:
ThreadPoolExecutor类的构造函数参数如下:
ThreadPoolExecutor executor = new ThreadPoolExecutor(2,5, 10, TimeUnit.SECONDS,new LinkedBlockingQueue<>()); executor.submit(() ->{ System.out.println("hello from thread pool"); }); executor.shutdown();
- 2:表示核心线程数,即线程池中始终保持的活动线程数。
- 5:表示最大线程数,即线程池中允许的最大线程数。
- 10:表示线程空闲时间,当线程池中的线程数超过核心线程数时,多余的线程在空闲时间超过这个值时会被回收。
- TimeUnit.SECONDS:表示时间单位,这里是秒。
- new LinkedBlockingQueue<>(): 表示用于存放任务的阻塞队列,这里是一个无界队列。
3.使用 ScheduledThreadPoolExecutor 类创建定时任务线程池:
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(3); executorService.schedule(() ->{ System.out.println("hello from thread pool"); },5,TimeUnit.SECONDS);//数字 5 表示延迟执行任务的时间 executorService.shutdown();
感谢大家观看!