使用 threadPoolTaskExecutor.getThreadPoolExecutor().getQueue().size()
即可。
示例:
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
public class TestThreadPool {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("xxxx-");
threadPoolTaskExecutor.setCorePoolSize(1);
threadPoolTaskExecutor.setMaxPoolSize(5);
threadPoolTaskExecutor.setQueueCapacity(5);
threadPoolTaskExecutor.setKeepAliveSeconds(300);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
System.out.println("丢弃");
}
});
threadPoolTaskExecutor.initialize();
int taskNum = 10;
List<Future> taskFutureList = new ArrayList<>();
for (int i=0; i < taskNum; i++) {
final int taskId = i;
System.out.println("-- submit task " + taskId);
Future future = threadPoolTaskExecutor.submit(() -> {
try {
System.out.printf("task: %s, thread: %s, start at %d\n", taskId, Thread.currentThread().getName(), System.currentTimeMillis()/1000);
Thread.sleep(2_000);
System.out.printf("task: %s, thread: %s, end at %d\n", taskId, Thread.currentThread().getName(), System.currentTimeMillis()/1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
taskFutureList.add(future);
}
// 获取任务队列中的任务数量
System.out.println("任务队列任务数量: " + threadPoolTaskExecutor.getThreadPoolExecutor().getQueue().size());
for (Future future : taskFutureList) {
future.get();
}
threadPoolTaskExecutor.shutdown();
}
}