1. 线程池与普通线程的效率对比
普通线程
//普通线程
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class NormalThread {
public static void main(String[] args) throws InterruptedException {
long currentTime = System.currentTimeMillis();
Random r = new Random();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
Thread thread = new Thread() {
@Override
public void run() {
list.add(r.nextInt(100));
}
};
thread.start();
thread.join();
}
System.out.println(list.size());
currentTime = System.currentTimeMillis() - currentTime;
System.out.println("currentTime = " + currentTime);
System.out.println("大小:" + list.size());
}
//currentTime = 13234
//大小:100000
}
线程池
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
public static void main(String[] args) throws InterruptedException {
long currentTime = System.currentTimeMillis();
Random r = new Random();
List<Integer> list = new ArrayList<>();
ExecutorService es = Executors.newSingleThreadExecutor();
for (int i = 0; i < 100000; i++) {
es.execute(() -> {
list.add(r.nextInt(100));
});
}
es.shutdown();
es.awaitTermination(1, TimeUnit.DAYS);
currentTime = System.currentTimeMillis() - currentTime;
System.out.println("currentTime = " + currentTime);
System.out.println("大小:" + list.size());
}
//currentTime = 65
//大小:100000
2. Executors类自带的三种线程池
1.newCachedThreadPool2.newFixedThreadPool
3.newSingleThreadPool
这三种线程池的本质都调用了ThreadPoolExecutor来创建线程池
2.1 newCachedThreadPool
每一个任务都会只会在队列中停留一下,然后被线程池的一个线程执行,
如果不出现线程复用,那么基本上多少个任务,就会开启多少个线程。
//这里用了Cached
public class ThreeExecutorsThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorService executorService1 = Executors.newFixedThreadPool(10);
ExecutorService executorService2 = Executors.newSingleThreadExecutor();
for (int i = 1; i <= 100; i++) {
executorService.execute(new MyTask(i));
}
}
}
class MyTask implements Runnable{
private int i = 0;
MyTask(int i){
this.i = i;
}
@Override
public void run() {
try {
//sleep1秒,模拟业务的执行
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程:" + Thread.currentThread().getName() + " --> i = " + i );
}
}
sleep1秒时:发现100个任务,100个线程。
不sleep时:发现最多只用了34个线程,这是因为任务完成太快,发生了线程的复用。
2.2 newFixedThreadPool
当我把上面代码执行者换为executorServer1时:
会发现它的执行,最多出现了10个线程,因为传入的参数为10
2.3 newSingleThreadPool
当我们翻开newSingleThreadPool的源码会发现:它和newFixedThreadPool方法的源码唯一的区别就是前者是只有一个线程在执行任务,后者是自定义线程去执行任务。
当我把上面代码执行者换为executorServer2时:
会发现它所有的任务都是由线程1去执行的
2.4 总结
newCachedThreadPool是执行最快的,
newFixedThreadPool执行相对较慢,
newSingleThreadPool执行最慢
但是这三种创建线程池的方式都有其弊端:
如果千万级的任务用这三种方法分别去创建线程池
-> Cached会创建千万级的线程,这会大大消耗cpu,使其“爆炸”。
-> Fixed和Single因为其队列是亿级的,会把千万级的任务都缓存到队列中,会使内存溢出。
3. 线程池的拒绝策略
我们首先创建一个自定义线程池,然后运行代码
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class RejectStrategy {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
10,
20,
30,
TimeUnit.SECONDS,
new LinkedBlockingDeque(10)
);
for (int i = 1; i <= 100; i++) {
threadPoolExecutor.execute(new MyTask1(i));
}
}
}
class MyTask1 implements Runnable {
private int i = 0;
MyTask1(int i) {
this.i = i;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程:" + Thread.currentThread().getName() + " --> i = " + i);
}
}
然后会发现在拒绝策略(在第31个任务执行时报错)出现后,竟然线程还在运行
出现的原因不是线程对cpu的抢占
而是线程池分为提交优先级和执行优先级
在源码中也有对应,当前任务数小于核心线程数时,任务提交到核心线程。
大于非核心线程数直接拒绝
这是执行优先级对应的源码
–>也就是任务不为空时,执行任务
–>任务为空时,从队列获取任务,执行任务
- CallerRunsPolicy - 当触发拒绝策略,只要线程池没有关闭的话,则使用调用线程直接运行任务。一般并发比较小,性能要求不高,不允许失败。但是,由于调用者自己运行任务,如果任务提交速度过快,可能导致程序阻塞,性能效率上必然的损失较大
- AbortPolicy - 丢弃任务,并抛出拒绝执行 RejectedExecutionException 异常信息。线程池默认的拒绝策略。必须处理好抛出的异常,否则会打断当前的执行流程,影响后续的任务执行。
- DiscardPolicy - 直接丢弃,其他啥都没有
- DiscardOldestPolicy - 当触发拒绝策略,只要线程池没有关闭的话,丢弃阻塞队列 workQueue 中最老的一个任务,并将新任务加入
4. execute和submit的区别
- execute只能提交Runnable类型的任务,无返回值。submit既可以提交Runnable类型的任务,也可以提交Callable类型的任务,会有一个类型为Future的返回值,但当任务类型为Runnable时,返回值为null。
- execute在执行任务时,如果遇到异常会直接抛出,而submit不会直接抛出,只有在使用Future的get方法获取返回值时,才会抛出异常。
参考资料:
https://www.bilibili.com/video/BV1u7411t7G1
https://www.cnblogs.com/jelly12345/p/15006708.html
https://www.cnblogs.com/jxxblogs/p/11882381.html