java 实现 有界阻塞队列的定时任务 ScheduledThreadPoolExecutor
时间: 2023-12-07 09:37:27 浏览: 175
下面是Java实现有界阻塞队列的定时任务ScheduledThreadPoolExecutor的方法和步骤:
1. 首先,需要导入java.util.concurrent.ScheduledThreadPoolExecutor类和java.util.concurrent.TimeUnit类。
2. 创建ScheduledThreadPoolExecutor对象,指定核心线程数和最大线程数,并设置有界阻塞队列的容量大小。
```java
int corePoolSize = 5; // 核心线程数
int maxPoolSize = 10; // 最大线程数
long keepAliveTime = 5000; // 线程空闲时间
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100); // 有界阻塞队列
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, queue);
```
3. 创建Runnable对象,表示要执行的任务。
```java
Runnable task = new Runnable() {
@Override
public void run() {
// 执行任务的代码
}
};
```
4. 调用ScheduledThreadPoolExecutor的schedule方法,指定任务和延迟时间。
```java
long delay = 1000; // 延迟时间
executor.schedule(task, delay, TimeUnit.MILLISECONDS);
```
这样就可以实现有界阻塞队列的定时任务了。
阅读全文
相关推荐


















