Furture模式是把一个任务拆成多个子任务,没有依赖关系的子任务来并行执运行的模式,旨在提高程序处理效率 假如说做饭需要三步,买菜(2秒)、买油(3秒)、炒菜(4秒)三步,其中买菜、买油可以两个人同时做,炒菜依赖买菜、买油的结果。
private String buyVegetable() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("buyVegetable done"); return "vegetable"; } private String buyOil() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("buyOil done"); return "oil"; } public void cooking(String oil, String vegetable) { log.info(oil + " and " + vegetable + " get, start cooking"); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("cooking done"); }测试代码:
private ExecutorService executor = Executors.newCachedThreadPool(); @Test public void testFuture() throws InterruptedException, ExecutionException { Long startTime = System.currentTimeMillis(); Future<String> vegetableFuture = executor.submit(this::buyVegetable); Future<String> oilFuture = executor.submit(this::buyOil); String oil = oilFuture.get(); String vegetable = vegetableFuture.get(); cooking(oil, vegetable); Long endTime = System.currentTimeMillis(); log.info("cost: " + (endTime - startTime)); }输出: 2020-07-02 20:26:40.765 - [pool-1-thread-1] INFO com.demo.util.FTPUtilTest : 47 - buyVegetable done 2020-07-02 20:26:41.764 - [pool-1-thread-2] INFO com.demo.util.FTPUtilTest : 57 - buyOil done 2020-07-02 20:26:41.764 - [main] INFO com.demo.util.FTPUtilTest : 62 - oil and vegetable get, start cooking 2020-07-02 20:26:45.779 - [main] INFO com.demo.util.FTPUtilTest : 68 - cooking done 2020-07-02 20:26:45.779 - [main] INFO com.demo.util.FTPUtilTest : 38 - cost: 7061 可以看到,买蔬菜和买油是两个线程执行的,总耗时似乎7秒左右而不是串行下的9秒
