1 //Executors 工具类
2 //使用线程池之后,使用线程池来创建线程
3 public class Dome1 {
4 public static void main(String[] args) {
5 ExecutorService threadExecutor = Executors.newSingleThreadExecutor();//单个线程
6 ExecutorService threadExecutor = Executors.newFixedThreadPool(5);//创建一个固定的线程大小
7 ExecutorService threadExecutor = Executors.newCachedThreadPool();//可伸缩,遇强则强,遇弱则弱
8 try {
9 for (int i = 0; i <=100; i++) {
10 //使用线程池之后,使用线程池来创建线程
11 threadExecutor.execute(()->{
12 System.out.println(Thread.currentThread().getName()+"ok");
13 });
14 }
15
16 } finally {
17 //线程池用完,程序结束,关闭线程池
18 threadExecutor.shutdown();
19 }
20 }
21 }
execute:

void execute(Runnable command);直接在里面就可以使用lambda

 

四大拒绝策略
1 public class Dome1 {
2 public static void main(String[] args) {
3 // ExecutorService threadExecutor = Executors.newSingleThreadExecutor();//单个线程
4 // ExecutorService threadExecutor = Executors.newFixedThreadPool(5);//创建一个固定的线程大小
5 // ExecutorService threadExecutor = Executors.newCachedThreadPool();//可伸缩,遇强则强,遇弱则弱
6 ExecutorService threadExecutor = new ThreadPoolExecutor(
7 //自定义线程池
8 2,//核心大小
9 5,//最大线程数
10 2,//超时不候
11 TimeUnit.SECONDS,//队列
12 new LinkedBlockingDeque<>(3),//候客区最大数
13 Executors.defaultThreadFactory(),
14 new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试和已获得的一个线程竞争,不会抛出异常
15 );
16
17 try {
18 //最大承载: capacity + maximum
19 for (int i = 1; i <=9; i++) {
20 //使用线程池之后,使用线程池来创建线程
21 threadExecutor.execute(()->{
22 System.out.println(Thread.currentThread().getName()+"ok");
23 });
24 }
25
26 } finally {
27 //线程池用完,程序结束,关闭线程池
28 threadExecutor.shutdown();
29 }
30 }
31 }
//Executors 工具类
//使用线程池之后,使用线程池来创建线程

/**
* 第一种
* new ThreadPoolExecutor.AbortPolicy()//如果空间已经忙了,后面还有要进了的线程,不处理这个
* 会报异常
* 第二种
* new ThreadPoolExecutor.CallerRunsPolicy()//哪里来的就去那里
* mainok
* 第三种
*new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常
* 第四种
*new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试和已获得的一个线程竞争,不会抛出异常
*/