目录
线程池是什么
线程池(Thread Pool)是一种多线程处理形式,主要的目的是控制和管理线程的创建,复用和销毁,以提高程序的性能和资源利用率.
其中线程池的最大好处就是减少每次启动,销毁线程的损耗.
标准库中的线程池
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
});
- 使用Executors.newFixedThreadPool(10)创建出固定包含10个线程的线程池
- 返回类型为Executorservice
- 通过ExecutorService.submit可以注册一个任务到线程池中
再例如下面的代码线程池中四个线程,然后一共创建100个任务,四个线程随机拿任务
public class Thread1 {
public static void main(String[] args) {
ExecutorService service= Executors.newFixedThreadPool(4);
//创建固定大小为4的线程池
for (int i = 0; i < 100; i++) {
int n=i;
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("执行任务"+n+ ",当前任务为"+Thread.currentThread().getName());
}
});
}
}
}
模拟实现线程池
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* Created with IntelliJ IDEA.
* Description:
* User: ShiHang
* Date: 2024-07-15
* Time: 22:05
*/
class MyThreadPoolExecutor{//executor接口
private List<Thread> threadList=new ArrayList<>();//创建动态数组用来放置所有线程
private BlockingQueue<Runnable>queue=new ArrayBlockingQueue<>(1000);
//创建阻塞队列,来保存所有的任务
//通过n来制定创建多少个线程
public MyThreadPoolExecutor(int n){//创建了一个构造方法,创建类的实例,初始化对象属性
for (int i = 0; i < n; i++) {
Thread t=new Thread(()->{
//线程要做的事情就是把任务队列中的任务取出来,并且执行
while (true){
try {
Runnable runnable=queue.take();//取出阻塞队列里的任务
runnable.run();//把取出来的任务执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
threadList.add(t);//把创建好的线程放到list里
}
}
public void submit (Runnable runnable) throws InterruptedException {
//提交任务的方法,放到阻塞队列中等待线程执行
queue.put(runnable);
}
}
public class MyThreadPool {
public static void main(String[] args) throws InterruptedException {
MyThreadPoolExecutor executor=new MyThreadPoolExecutor(5);
for (int i = 0; i < 1000; i++) {
int n=i;
executor.submit(new Runnable() {
@Override
public void run() {
System.out.println("执行任务"+n+ ",当前任务为"+Thread.currentThread().getName());
}
});
}
}
}