1.线程池接口介绍
先看下图
Executor是最原始的接口,内部只有一个方法execute(),然后是我们比较常见的ExecutorService他是Executor的子接口内部实现了若干方法,例如shutdown()方法,submit()方法等。
ExecutorService有一个唯一实现它的子类AbstractExcutorService
但是无奈这是个抽象类,无法实例化,但是其有一个子类ThreadPoolExector是可以实例化的实体类。
但是直接使用起来比较麻烦,因为他有一堆参数需要填,就是线程池那一堆balabala。。。所以官方建议的是使用Executor实现类。里面已经将各种类型的线程池的入参设计好,只需明白具体的含义,直接调用即可。如下图所示
ExecutorService executorService = Executors.newCachedThreadPool();
2.如何使用线程池
public class MyRunnable implements Runnable {
private String username;
public MyRunnable(String username) {
super();
this.username = username;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " username= " + username + " begin " + System.currentTimeMillis());
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " username= " + username + " end " + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//创建一个不定长的线程池
ExecutorService executorService = Executors.newCachedThreadPool();
IntStream.range(0,5).forEach(i->executorService.execute(new MyRunnable(""+(i+1))));
循环新建五个线程放入线程池,然后执行,结果如下
pool-1-thread-1 username= 1 begin 1624431339065
pool-1-thread-2 username= 2 begin 1624431339065
pool-1-thread-3 username= 3 begin 1624431339065
pool-1-thread-4 username= 4 begin 1624431339065
pool-1-thread-5 username= 5 begin 1624431339065
pool-1-thread-4 username= 4 end 1624431340066
pool-1-thread-2 username= 2 end 1624431340066
pool-1-thread-1 username= 1 end 1624431340066
pool-1-thread-3 username= 3 end 1624431340066
pool-1-thread-5 username= 5 end 1624431340066
日常开发过程中,可以直接new Runnable(){ //逻辑代码}即可实现。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, 2147483647, 60L, TimeUnit.SECONDS, new SynchronousQueue());
}
不过这个线程池入参没有阻塞队列,也可以自行的配置参数添加阻塞队列,防止
创建过多的线程导致CPU爆掉或者内存溢出等问题。