import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; class Task implements Runnable { private int id; public Task(int id) { this.id = id; } @Override public void run() { System.out.println(String.format("id = %d is running.", id)); try { Thread.sleep(100000000 * 100); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { LinkedBlockingQueue<Runnable> taskPool = new LinkedBlockingQueue<>(5); ThreadPoolExecutor threads = new ThreadPoolExecutor(1, 4, 5L, TimeUnit.SECONDS, taskPool); int i = 0; threads.submit(new Task(++i)); Task task = new Task(++i); threads.submit(task); for (int j = 0; j < 100; j++) { if(taskPool.size()==5){ System.out.println(); } threads.submit(new Task(++i)); } System.out.println(); }
备注:
/** * * @param corePoolSize 核心数,也是线程池的基础线程数。不论线程是否限制,corePoolSize个线程不会被销毁 * @param maximumPoolSize 最大线程数,只有当workQueue队列满了才会在corePoolSize个线程基础之上进行扩容到maximumPoolSize数; * 扩容到最大数目之后workQueue还是满的话,将会报错RejectedExecutionException。当然你也可以添加拒绝策略 * @param keepAliveTime 超过corePoolSize数目线程,闲置时间,超时被销毁。 * @param unit 时间单位 * @param workQueue Task队列 */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue);
public static void main(String[] args) { RejectedExecutionHandler reject = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { // 各种策略吧 System.out.println("将任务存储到数据库或者Redis中缓冲,然后再启动一个轮询的Thread负责在空闲的时候进行再次提交!"); } }; System.out.println(reject.getClass()); LinkedBlockingQueue<Runnable> taskPool = new LinkedBlockingQueue<>(5); ThreadPoolExecutor threads = new ThreadPoolExecutor(1, 4, 5L, TimeUnit.SECONDS, taskPool, new BasicThreadFactory.Builder().namingPattern("task-thread-pool-%d").build(), reject); int i = 0; threads.submit(new Task(++i)); Task task = new Task(++i); threads.submit(task); for (int j = 0; j < 100; j++) { if (taskPool.size() == 5) { System.out.println(); } threads.submit(new Task(++i)); } System.out.println(); }