线程池
import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolService { private static final int DEFAULT_CORE_SIZE=100; private static final int MAX_QUEUE_SIZE=500; private volatile static ThreadPoolExecutor executor; private ThreadPoolService() {}; // 获取单例的线程池对象 public static ThreadPoolExecutor getInstance() { if (executor == null) { synchronized (ThreadPoolService.class) { if (executor == null) { executor = new ThreadPoolExecutor(DEFAULT_CORE_SIZE,// 核心线程数 MAX_QUEUE_SIZE, // 最大线程数 Integer.MAX_VALUE, // 闲置线程存活时间 TimeUnit.MILLISECONDS,// 时间单位 new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE),// 线程队列 Executors.defaultThreadFactory()// 线程工厂 ); } } } 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); } } }
测试代码:
@Test public void threadPool() { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); Date startDate = new Date(); System.out.println("开始时间:"+sf.format(startDate)); for(int i=0;i<300000;i++) { System.out.println("i=" + i); //启动线程 ThreadPoolService.getInstance().execute(() -> { int total = 0; for (int k = 0; k < 1000; k++) { total = total + k; } System.out.println("total=" + total); }); } System.out.println("结束了"); Date endDate = new Date(); System.out.println("结束时间:" + sf.format(endDate)); System.out.println("耗时,单位秒:" + (endDate.getTime() - startDate.getTime()) / 1000); ThreadMXBean bean = ManagementFactory.getThreadMXBean(); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程总数为 = " + bean.getThreadCount()); long activeCount = ThreadPoolService.getInstance().getActiveCount(); System.out.println("活跃线程总数为 = " + activeCount); long largestPoolSize = ThreadPoolService.getInstance().getLargestPoolSize(); System.out.println("曾经同时位于池中的最大线程数为 = " + largestPoolSize); long poolSize = ThreadPoolService.getInstance().getPoolSize(); System.out.println("池中的当前线程数为 = " + poolSize); }
运行结果: