package com.chen.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test1 {
public static void main(String[] args) {
// 平时我们创建一些类使用工具类操作 s
// 总数可以管理
// 线程池 Executors原生三大方法
ExecutorService threadpool1 = Executors.newFixedThreadPool(50); // 固定大小
// ExecutorService threadpool2 = Executors.newCachedThreadPool(); //可以弹性伸缩的线程池,遇强则强
//ExecutorService threadpool3 = Executors.newSingleThreadExecutor(); // 只有一个
try {
// 10个线程,会显示几个线程~
for (int i = 1; i <= 100; i++) {
// 线程池,执行线程
threadpool1.execute(()->{
System.out.println(Thread.currentThread().getName()+" running...");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池关闭
threadpool1.shutdown();
}
}
}
====================线程池ExecutorService =================================
public static void main(String[] args) {
// 代码级别的
System.out.println(Runtime.getRuntime().availableProcessors());
ExecutorService threadPool = new ThreadPoolExecutor(
2,
Runtime.getRuntime().availableProcessors(), // 线程池最大大小5
2L,
TimeUnit.SECONDS, // 超时回收空闲的线程,假设超过了指定的时间,这个最大的线程就不被
new LinkedBlockingDeque<>(3), // 根据业务设置队列大小,队列大小一定要设置
Executors.defaultThreadFactory(), // 不用变
new ThreadPoolExecutor.CallerRunsPolicy() //拒绝策略
);
// 拒绝策略说明:
// 1. AbortPolicy (默认的:队列满了,就丢弃任务抛出异常!)
// 2. CallerRunsPolicy(哪来的回哪去? 谁叫你来的,你就去哪里处理)
// 3. DiscardOldestPolicy (尝试将最早进入对立与的人任务删除,尝试加入队列)
// 4. DiscardPolicy (队列满了任务也会丢弃,不抛出异常)
try {
// 队列 RejectedExecutionException 拒绝策略
for (int i = 1; i <= 20; i++) {
// 默认在处理
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+" running....");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
标签:java,Executors,队列,线程,new,ExecutorService
From: https://www.cnblogs.com/chenshaojun2008/p/18229544