什么是线程池?未使用线程池调用任务方式ThreadPool线程池
ThreadPool线程池类图线程池优点线程池调用任务 ThreadPoolExecutor创建线程池
ThreadPoolExecutor中方法ThreadPoolExecutor参数说明自定义线程工厂创建任务原生线程池调用任务
什么是线程池?线程池是一种基于池化思想管理线程的工具 未使用线程池调用任务方式
首先创建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;
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中方法
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
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;
}
}
创建任务
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;
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(),
new CustomThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
// 提交任务
threadPool.execute(task1);
threadPool.execute(task2);
threadPool.execute(task3);
// 关闭线程池
threadPool.shutdown();
}
}
输出结果
参考地址:线程池视频讲解.



