1、线程的创建是很费资源的,因此为了减少线程的创建,将线程统一管理,变得可复用。
2、传统的方式可能会出现一个请求就要创建一个线程,可能会遇到恶意请求导致资源耗尽宕机、但是使用线程池可以控制线程的创建,防止因为消耗过多内存导致服务器崩溃。
package a;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
public class MyExecute {
//线程停止标记
private boolean isRun = true;
//任务队列
LinkedBlockingDeque<Runnable> linkedBlockingDeque;
//线程集合 new ArrayList有线程问题会导致remove出现问题
List<Thread> threadList;
//传入核心线程数量、最大线程数量。后期可以自己改造增加队列长度限制等。
public MyExecute(int size,int maxSize) {
linkedBlockingDeque=new LinkedBlockingDeque<>();
threadList= Collections.synchronizedList(new ArrayList<>());
execute(size,maxSize);
}
public void execute(int size,int maxSize){
//新建几个默认的线程
for(int i=0;i<size;i++){
int finalI = i;
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
while (isRun||linkedBlockingDeque.size()>0){
if(finalI ==0){
//判断是否需要增加线程的数量
addThread(maxSize);
}
Runnable runnable=linkedBlockingDeque.poll();
if(runnable!=null){
runnable.run();
}else{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
threadList.add(thread);
thread.start();
}
}
public void addThread(int maxSize){
if(this.threadList.size()<maxSize){
for(int i=0;i<linkedBlockingDeque.size()-2&&threadList.size()<maxSize;i++){
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
int flag=3;
while (isRun||linkedBlockingDeque.size()>0){
Runnable runnable=linkedBlockingDeque.poll();
if(runnable!=null){
runnable.run();
}else{
//将空闲的线程销毁
if(flag==0){
break;
}else{
//将空闲的线程等待300毫秒后再执行
try {
Thread.sleep(1000);
flag--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
threadList.remove(Thread.currentThread());
}
});
threadList.add(thread);
thread.start();
}
}
}
public static void main(String[] args) {
MyExecute execute=new MyExecute(2,100);
for (int i=0;i<800;i++){
int finalI = i;
//在线程池中加入需要执行的任务
execute.linkedBlockingDeque.push(new Runnable() {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName()+",i:"+ finalI+"当前线程数量"+ execute.threadList.size()+",待执行的任务书:"+ execute.linkedBlockingDeque.size());
try {
//模拟任务的执行,每个任务执行需要1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//模拟各时间段 线程池随着任务量的多少,自动创建或销毁
try {
if(i<10){
Thread.sleep(800);
}else if(i<200){
// Thread.sleep(50);
}else if(i<230){
Thread.sleep(3000);
}else if(i<270){
Thread.sleep(400);
}else if(i<280){
Thread.sleep(2000);
}else{
Thread.sleep(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
execute.isRun=false;
}
}