import java.util.concurrent.*;
/** |-> 小于corePoolSize -> 分配线程执行
* 任务提交-> | |->成功->等待执行
* |-> 大于corePoolSize -> 提交到等待队列 ->| |->达到maximumPoolSize线程,提交失败->拒绝执行
* |->失败->提交线程池->|
* |->未达到,提交成功->分配线程执行
*
* 自定义线程池和拒绝策略的使用
*/
public class RejectThreadPoolDemo {
public static class MyTask implements Runnable{
@Override
public void run() {
System.out.println(System.currentTimeMillis()+" Id:"+Thread.currentThread().getId());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException{
MyTask task = new MyTask();
/**
* public ThreadPoolExecutor(int corePoolSize, //指定线程池中线程数量
* int maximumPoolSize, //指定线程池中的最大线程数量
* long keepAliveTime, //超过corePoolSize的空闲线程,在多长时间内会被销毁
* TimeUnit unit, //keepAliveTime的单位
* BlockingQueue<Runnable> workQueue,//任务队列
* ThreadFactory threadFactory,//线程工厂,一般默认即可
* RejectedExecutionHandler handler) {//拒绝策略,当任务太多来不及处理,如何拒绝任务
*/
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10),
Executors.defaultThreadFactory(), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { //r:请求执行的任务 executor:当前的线程池
//打印丢失的任务
System.out.println(r.toString() + " is discard");
}
});
for (int i = 0; i < Integer.MAX_VALUE; i++) {
executor.submit(task);
Thread.sleep(10);
}
}
//1567644472625 Id:9
//1567644472631 Id:10
//1567644472646 Id:11
//1567644472654 Id:12
//1567644472665 Id:13
//java.util.concurrent.FutureTask@60e53b93 is discard
//java.util.concurrent.FutureTask@5e2de80c is discard
//。。。
}