针对io密集型任务,可以采用多线程方式处理,其消耗时间比单线程大幅度减少。
import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; @Slf4j public class ThreadPoolTest { public void multiThread(int num) { long start = System.currentTimeMillis(); log.info("start ...."); //声明线程池 // ExecutorService executor = Executors.newFixedThreadPool(8); //针对IO密集型的任务 int nThreads = Runtime.getRuntime().availableProcessors() * 2; log.info("nThreads:{}",nThreads); ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); //该拒绝策略,首先判断线程池是否关闭,如果未关闭,则直接执行该线程 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); List<Future<Integer>> futures = new ArrayList<>(); //批量提交任务 for (int i = 0; i < num; i++) { int finalI = i; futures.add( executor.submit( //线程任务 new Callable<Integer>() { @Override public Integer call() throws Exception { task(finalI); return finalI; } } )); } //获取执行完的结果 for (Future<Integer> future : futures) { try { log.info(String.valueOf(future.get())); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } log.info("end cost {} ....", System.currentTimeMillis() - start); //关闭线程池 executor.shutdown(); } //要执行的任务,耗时200ms private void task(int num) { try { log.info(" task:{} ,currentThread: {} ", num, Thread.currentThread().getName()); Thread.sleep(200L); } catch (InterruptedException e) { e.printStackTrace(); } } //单线程执行 public void singleThread(int num) { long start = System.currentTimeMillis(); log.info("start ...."); for (int i = 0; i < num; i++) { task(i); } log.info("end cost {} ....", System.currentTimeMillis() - start); } public static void main(String[] args) { ThreadPoolTest concurrentTest = new ThreadPoolTest(); //单线程耗时2秒 // concurrentTest.singleThread(10); //多线程耗时200毫秒 concurrentTest.multiThread(10); } }
本文摘自 :https://www.cnblogs.com/