import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class DiscardPolicyDemo { private static final int corePoolSize = 3; private static final int maximumPoolSize = 6; private static final int QueueCAPACITY = 10; public static void main(String[] args) throws Exception { // 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE),"线程池"的阻塞队列容量为1(CAPACITY)。 ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QueueCAPACITY),new rejectedImpl()); // 设置线程池的拒绝策略为"丢弃" // 新建10个任务,并将它们添加到线程池中。 for (int i = 0; i < 20; i++) { Runnable myrun = new MyRunnable("task-"+i); pool.execute(myrun); } // 关闭线程池 pool.shutdown(); } } class rejectedImpl implements RejectedExecutionHandler{ @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.println(String.format("Task %s rejected.", r.hashCode())); } }
class MyRunnable implements Runnable { private String name; public MyRunnable(String name) { this.name = name; } @Override public void run() { try { System.out.println(this.name + " is running."); Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } } }
运行结果:
task-2 is running. task-0 is running. task-1 is running. task-13 is running. task-14 is running. task-15 is running. Task 460141958 rejected. Task 312714112 rejected. Task 692404036 rejected. Task 1554874502 rejected. task-3 is running. task-5 is running. task-4 is running. task-6 is running. task-7 is running. task-8 is running. task-9 is running. task-12 is running. task-11 is running. task-10 is running.
Java自带的线程池ThreadPoolExecutor详细介绍说明和实例应用
http://fulong258.blog.163.com/blog/static/17895044201082951820935