线程池:系列一
什么是线程池?
- 线程池是一种基于池化思想管理线程的工具
未使用线程池调用任务方式
- 首先创建Task任务类实现Runable,并输出线程名称
public class Task implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
- 启动线程
public class ThreadPool01 {
public static void main(String[] args) {
ThreadPool01.test01();
}
/**
* 线程不能复用,重复创建和销毁线程耗时耗资源
**/
private static void test01(){
// 创建任务
Runnable task1 = new Task();
Runnable task2 = new Task();
Runnable task3 = new Task();
// 创建线程
Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
Thread thread3 = new Thread(task3);
// 启动线程
thread1.start();
thread2.start();
thread3.start();
}
}
- 输出结果
ThreadPool线程池
ThreadPool线程池类图
ThreadPool线程池类图
线程池优点
- 降低资源消耗:通过重复利用已创建的线程降低创建和销毁造成的消耗
- 提高响应速度:当又任务时,任务可以不需要等到线程创建就能立即执行
- 提高线程的可管理型:线程池可以进行统一的分配,调优和监控
线程池调用任务
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description 线程池:线程池是一种基于池化思想管理线程的工具
**/
public class ThreadPool01 {
public static void main(String[] args) {
ThreadPool01.test02();
}
/**
* 线程池执行任务
* 优点:
* 降低资源消耗:通过重复利用已创建的线程降低创建和销毁造成的消耗
* 提高响应速度:当又任务时,任务可以不需要等到线程创建就能立即执行
* 提高线程的可管理型:线程池可以进行统一的分配,调优和监控
**/
private static void test02(){
// 创建任务
Runnable task1 = new Task();
Runnable task2 = new Task();
Runnable task3 = new Task();
// 创建只有一个线程的线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();
// 提交任务
threadPool.execute(task1);
threadPool.execute(task2);
threadPool.execute(task3);
// 关闭线程池
threadPool.shutdown();
}
- 输出结果
ThreadPoolExecutor创建线程池
ThreadPoolExecutor中方法
ThreadPoolExecutor参数说明
自定义线程工厂
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description 自定义线程工厂
* @ClassName CustomThreadFactory
* @Date 2022/2/6 21:18
**/
public class CustomThreadFactory implements ThreadFactory {
// 计数器
private final AtomicInteger i = new AtomicInteger(1);
public Thread newThread(Runnable r) {
// 创建线程,并指定任务
Thread thread = new Thread(r);
// 设置线程名称
thread.setName("线程" + i.getAndIncrement() + "号");
// 返回线程
return thread;
}
}
创建任务
/**
* @Description
* @ClassName Task
* @Date 2022/2/6 20:56
**/
public class Task implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
原生线程池调用任务
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @Description 原生方式创建线程池,阿里开发推荐的一种
* @ClassName ThreadPool02
* @Date 2022/2/6 21:12
**/
public class ThreadPool02 {
public static void main(String[] args) {
// 创建任务
Runnable task1 = new Task();
Runnable task2 = new Task();
Runnable task3 = new Task();
// 创建线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10,25,10, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new CustomThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
// 提交任务
threadPool.execute(task1);
threadPool.execute(task2);
threadPool.execute(task3);
// 关闭线程池
threadPool.shutdown();
}
}
- 输出结果