写在前头
本例自己学习使用,欢迎各位大佬批评指正~
Action >>>
package com.thread.study;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @Description DCLThreadPool :
* @Author Sr
* @Date 2021/8/19
*/
public class DCLThreadPoolService {
/** 核心线程数 */
private static final int CORE_POOL_SIZE = 100;
/** 最大线程数 */
private static final int MAXIMUM_POOL_SIZE = 500;
/** 闲置线程存活时间 */
private static final int KEEP_ALIVE_TIME = 60;
/** 工作队列最大大小 */
private static final int WORK_QUEUE_SIZE = 6666;
private volatile static ThreadPoolExecutor executor = null;
private DCLThreadPoolService() {};
/**
* 获取单例的线程池对象
*/
public static ThreadPoolExecutor getInstance() {
if (executor == null) {
synchronized (DCLThreadPoolService.class) {
if (executor == null) {
executor = new ThreadPoolExecutor(
/** 核心线程数 */
CORE_POOL_SIZE,
/** 最大线程数 */
MAXIMUM_POOL_SIZE,
/** 闲置线程存活时间 */
KEEP_ALIVE_TIME,
/** 时间单位 */
TimeUnit.MILLISECONDS,
/** 线程队列 */
new LinkedBlockingDeque<Runnable>(WORK_QUEUE_SIZE),
/** 线程工厂 */
Executors.defaultThreadFactory(),
/** 拒绝策略 使用JDK默认的4种中的 CallerRunsPolicy(当超出阻塞队列后 让主线程执行超出的任务) 此处也可以自定义拒绝策略 */
new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()
);
}
}
}
return executor;
}
public void execute(Runnable runnable) {
if (runnable == null) {
return;
}
executor.execute(runnable);
}
/**
* 从线程队列中移除对象
*/
public void cancel(Runnable runnable) {
if (executor != null) {
executor.getQueue().remove(runnable);
}
}
}
测试使用
package com.thread.study;
import java.util.concurrent.*;
/**
* @Description TestExcutor :
* @Author Sr
* @Date 2021/8/20
*/
public class TestTPE {
public static void getData(long time) {
try {
TimeUnit.MILLISECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(Thread.currentThread().getName() + " ");
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
int size = 50;
CountDownLatch countDownLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
DCLThreadPoolService.getInstance().execute(new Thread(() ->{
try {
getData(2000);
} catch (Exception e){
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}, "Thread-"+ i));
}
try {
countDownLatch.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n总消耗:" + (System.currentTimeMillis() - start) + "ms");
}
}