使用示例
class RunnableThread implements Runnable {
@Override
public void run() {
System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName() + " ");
}
}
public class Test {
public static void main(String[] args) throws Exception{
ExecutorService executorService = new ThreadPoolExecutor(
2, //核心线程数
Runtime.getRuntime().availableProcessors(), //最大线程数,cpu 核数
3, //超时时间
TimeUnit.SECONDS, //超时单位
new LinkedBlockingDeque<>(3), //等待队列
Executors.defaultThreadFactory(), //线程工厂
new ThreadPoolExecutor.AbortPolicy()); //拒绝策略
for(int i = 0; i<8; i++) {
RunnableThread thread = new RunnableThread();
executorService.execute(thread);
}
//关闭线程池
executorService.shutdown();
}
}
结果:
通过线程池方式创建的线程:pool-1-thread-1
通过线程池方式创建的线程:pool-1-thread-4
通过线程池方式创建的线程:pool-1-thread-3
通过线程池方式创建的线程:pool-1-thread-2
通过线程池方式创建的线程:pool-1-thread-4
通过线程池方式创建的线程:pool-1-thread-3
通过线程池方式创建的线程:pool-1-thread-5
通过线程池方式创建的线程:pool-1-thread-2