Java 实现Demo
package com.logan;import java.util.concurrent.*;/*** 线程池测试类* @author logan* @Date 2019年05月08日23:40:49*/ public class MyThreadTester {public static void main(String[] args) {// 获取自定义线程池MyThreadPool myThreadPool = MyThreadPool.getThreadPool();//执行myThreadPool.execute(new MyThread());//关闭资源myThreadPool.close();}}/*** 自定义线程池** 线程池的好处* 1.重用-避免线程的重复创建和销毁。这是很大的开销。* 2.控制并发数-线程池可以控制并发数。以达到对公共资源访问进行限流,从而达到削峰的效果。* 3.线程池可以批量管理,比方说可以定时、定期的执行一些任务等(e.g. Executors.newScheduledThreadPool)。**/ class MyThreadPool {private int corePoolSize;private int maxNumPoolSize;private long keepAliveTime;private static MyThreadPool theThreadPool;private ThreadPoolExecutor threadPoolExecutor;/**** @param corePoolSize 处理器个数* @param maxNumPoolSize 最大线程个数* @param keepAliveTime 存活时间 单位:秒*/private MyThreadPool(int corePoolSize, int maxNumPoolSize, long keepAliveTime){this.corePoolSize = corePoolSize;this.maxNumPoolSize = maxNumPoolSize;this.keepAliveTime = keepAliveTime;}public void execute(Runnable r){if(r == null)return ;if(threadPoolExecutor == null){threadPoolExecutor = new ThreadPoolExecutor(this.corePoolSize, //maxNumPoolSize, // 最大线程个数keepAliveTime, // 存活时间TimeUnit.SECONDS, // 存活时间单位new LinkedBlockingDeque<Runnable>(), // 阻塞双端队列,方便于从头尾,插入读取数据Executors.defaultThreadFactory(), // thread工厂,默认工厂就是一个起名new ThreadPoolExecutor.AbortPolicy()//拒绝策略,回绝并抛出RejectedExecutionException);}threadPoolExecutor.execute(r);}public static MyThreadPool getThreadPool(){// 单例if(theThreadPool == null){synchronized (MyThreadPool.class){if(theThreadPool == null){// 获取处理器个数int maxCoreSize = Runtime.getRuntime().availableProcessors();int maxThreadNum = maxCoreSize * 2 + 1; // 计算合理并发个数theThreadPool = new MyThreadPool(maxCoreSize,maxThreadNum,0L);}}}return theThreadPool;}/*** 关闭资源*/public void close(){if(threadPoolExecutor != null){threadPoolExecutor.shutdown();}}}class MyThread implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " Hello, Logan!!!");} }
详细解决方案
线程池的好处和实现
热度:38 发布时间:2023-09-30 04:55:46.0
相关解决方案