java中多ThreadPool配合
java线程池的默认实现是:超出核心线程数在运行时,有新任务是先进入线程队里,队列满了再启动非核心线程.
可以通过多个线程池配合,实现先启动非核心线程,再放入队列.
示例代码
public static void main(String[] args) throws Exception {
ThreadPoolExecutor executorAnother = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue(100) {
public boolean offer(Runnable e) {
System.out.println("another queue");
return super.offer(e);
}
});
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue(1) {
public boolean offer(Runnable e) {
return false;
}
}, new GiveToAnotherPolicy(executorAnother));
AtomicInteger atomicInteger = new AtomicInteger();
for (int i = 0; i < 5; i++) {
executor.submit(() -> {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.getAndIncrement());
});
}
Thread.sleep(6000L);
executorAnother.shutdown();
executor.shutdown();
}
static class GiveToAnotherPolicy implements RejectedExecutionHandler {
private ExecutorService executorAnother;
public GiveToAnotherPolicy(ExecutorService executorAnother) {
this.executorAnother = executorAnother;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("give to another");
executorAnother.submit(r);
}
}
输出
0
1
give to another
2
give to another
3
give to another
another queue
4