Java并行执行任务

/**
 * 并行执行任务
 */
public class TestFuture {

    @Test
    public void test(){

        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> method1());
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> method2());

        try {
            System.out.println(future1.get());
            System.out.println(future2.get());
        }catch (Exception e){

        }

    }

    public String method1(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "method1";
    }

    private String method2(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "method2";
    }

}

发表评论

邮箱地址不会被公开。 必填项已用*标注