创建ScheduledExecutorService的几种方式
时间: 2024-01-06 19:25:47 浏览: 76
基于ScheduledExecutorService的两种方法(详解)
以下是创建ScheduledExecutorService的几种方式:
1. 使用Executors类的newScheduledThreadPool方法创建一个固定大小的线程池:
```java
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
```
2. 使用Executors类的newSingleThreadScheduledExecutor方法创建一个只有一个线程的线程池:
```java
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
```
3. 使用Executors类的newScheduledThreadPool方法创建一个可缓存的线程池,线程数根据需要自动增加或减少:
```java
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(0);
```
4. 使用ThreadPoolExecutor类的构造方法创建一个自定义的ScheduledExecutorService:
```java
ScheduledExecutorService scheduledExecutorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
```
阅读全文