多線程編程七-Furture模式

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秒

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章