任务类:
package cm.pool;public class MyTask implements Runnable { private int taskId; private String taskName; public MyTask(int taskId, String taskName) { this.taskId = taskId; this.taskName = taskName; } public int getTaskId() { return taskId; } public void setTaskId(int taskId) { this.taskId = taskId; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"-----------run taskId="+this.taskId); Thread.sleep(5*1000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString() { return "MyTask [taskId=" + taskId + ", taskName=" + taskName + "]"; }}
拒绝策略类:
package cm.pool;import java.util.concurrent.RejectedExecutionHandler;import java.util.concurrent.ThreadPoolExecutor;public class MyRejected implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.println("自定义拒绝策略....."); System.out.println("当前被拒绝的任务------"+Thread.currentThread().getName()+":"+r.toString()); } }
使用拒绝策略:
package cm.pool;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;/** * @author Administrator * 1.使用有界队列时,若有新的任务执行,如果线程池实际线程不小于corsize,则优先创建线程。 * 2.若大于corsize,则将任务加入到队列中,等待第一个任务执行完成之后在执行队列里的任务。 * 3.若队列中的任务已满,则在总线程数不大于maxsize前提下,创建一个新的线程(此时已经创建两个线程先执行了两次任务,然后执行队列里存放了的三个任务) * 4.若线程数大于maxsize,则执行拒绝策略,获取其他自定义方法。 */public class UseThreadpoolExecutor_1 { public static void main(String[] args) { ThreadPoolExecutor pool = new ThreadPoolExecutor(1, // corSize 2, // maxPoolSize 60, // keepAliveTime TimeUnit.SECONDS, // unit, new ArrayBlockingQueue(3),// workQueue new MyRejected() ); MyTask task1 = new MyTask(1, "任务1"); MyTask task2 = new MyTask(2, "任务2"); MyTask task3 = new MyTask(3, "任务3"); MyTask task4 = new MyTask(4, "任务4"); MyTask task5 = new MyTask(5, "任务5"); MyTask task6 = new MyTask(6, "任务6"); pool.execute(task1); //2、3、4会放到队列 pool.execute(task2); pool.execute(task3); pool.execute(task4); pool.execute(task5); pool.execute(task6); pool.shutdown(); }}
运行结果:
pool-1-thread-2-----------run taskId=5自定义拒绝策略.....pool-1-thread-1-----------run taskId=1当前被拒绝的任务------main:MyTask [taskId=6, taskName=任务6]pool-1-thread-2-----------run taskId=2pool-1-thread-1-----------run taskId=3pool-1-thread-1-----------run taskId=4