public class Test {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(2,
5, 0, TimeUnit.DAYS,
new ArrayBlockingQueue<>(2), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
return thread;
}
});
executorService.execute(() -> {
System.out.println("任务1@" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
});
//回复字数限制问题不能贴完全代码,复制executorService.execute块,修改输出任务数字1-7
}
}
任务1@Thread-0
任务2@Thread-1
任务5@Thread-2
任务6@Thread-3
任务7@Thread-4
任务3@Thread-1
任务4@Thread-4
任务5,6, 7比任务3,4运行的早,看起来3和4都是被加到队列里了,队列满了后,新进来的任务(5,6,7)是直接创建线程执行的,然后再从队列头开始执行,所以是不是新任务来了不是必须经过队列的(5,6,7)