package concurrent;
import java.util.concurrent.*;
public class C01_Threadpool {
/**
* .使用自定义线程池与拒绝策略.详见《实战JAVA高并发程序设计》P103
* .注意!!!!不建议直接使用ThreadPoolExecutor,而是要对它进行加强。原因是
* ThreadPoolExecutor不能够得到异常消息,一旦发生错误将无迹可寻。
* .具体看C03_TraceThreadPoolExecutor,或《实战JAVA高并发程序设计》P113 3.2.8
*/
public static void main(String[] args) throws InterruptedException{
//定义提交的任务
Runnable task = () -> {
System.out.println(System.currentTimeMillis() + ":Thread ID:" + Thread.currentThread().getId());
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
};
//定义拒绝策略
RejectedExecutionHandler reject = (r, executor) -> System.out.println(r.toString() + " is discard...");
//创建线程池
ExecutorService es = new ThreadPoolExecutor(
3, //核心线程数
5, //最大线程数
60L, //空闲线程生存时间
TimeUnit.SECONDS, //空闲线程生存时间的单位
new LinkedBlockingDeque<Runnable>(5),//无法分配线程时的预备队列(若队列也满又出现新的任务,那么使用拒绝策略)
Executors.defaultThreadFactory(), //使用默认的线程工厂创建线程
reject //使用自定义的拒绝策略,在这里我们可以将信息反馈到日志中
);
//提交任务
for(int i=0 ; i<15 ; i++){
es.submit(task);
Thread.sleep(10);
}
es.shutdown(); //发送一个信号给线程池,线程池在完成当前所有任务后关闭
System.out.println("当前可用处理器个数:" + Runtime.getRuntime().availableProcessors());
}
}
console
1550995388971:Thread ID:11
1550995388981:Thread ID:12
1550995388991:Thread ID:13
1550995389052:Thread ID:14
1550995389061:Thread ID:15
java.util.concurrent.FutureTask@4eec7777 is discard...
java.util.concurrent.FutureTask@3b07d329 is discard...
java.util.concurrent.FutureTask@41629346 is discard...
java.util.concurrent.FutureTask@404b9385 is discard...
java.util.concurrent.FutureTask@6d311334 is discard...
当前可用处理器个数:8
1550995389972:Thread ID:11
1550995389981:Thread ID:12
1550995389991:Thread ID:13
1550995390052:Thread ID:14
1550995390062:Thread ID:15