Runnable:
@Test public void testFixedThreadPool() { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { final int index = i; fixedThreadPool.execute(() -> { try { log.info("newFixedThreadPool,index:{}", index); } catch (Exception e) { log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage()); } }); } fixedThreadPool.shutdown(); while(true){ if(fixedThreadPool.isTerminated()){ log.info("endd"); break; } } log.info("end"); }
Callable:
@Test public void testCallable() { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10); List> resultList = Lists.newArrayList(); for (int i = 0; i < 10; i++) { final int index = i; Future future = fixedThreadPool.submit(() -> { try { Thread.sleep(2000); log.info("newFixedThreadPool,index:{}", index); } catch (Exception e) { log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage()); } return "success"; }); resultList.add(future); } resultList.forEach(x -> { try { log.info("result:{}", x.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { fixedThreadPool.shutdownNow(); e.printStackTrace(); return; } }); log.info("end"); }