其他分享
首页 > 其他分享> > 异步执行

异步执行

作者:互联网

public void execute(){
        //来一个线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);
        CompletableFuture<Integer> future1= CompletableFuture.supplyAsync(new Supplier<Integer>()
        {
            @Override
            public Integer get() {
                for(int i=0;i<10;i++) {
                    System.out.println("task1:"+i);
                    sleep(1000);
                }
                
                return 333;
            }
        },executor);
        
        
        CompletableFuture<Integer> future2 =CompletableFuture.supplyAsync(new Supplier<Integer>()
        {
            @Override
            public Integer get() {
                for(int i=0;i<10;i++) {
                    System.out.println("task2:"+i);
                    sleep(1000);
                }
                return 666;
            }
        },executor);
        
        //等待所有任务执行结束
        CompletableFuture<Void> all= CompletableFuture.allOf(future1,future2);
        all.thenAccept(e->{
            //关闭线程池
            executor.shutdown();
            System.out.println("执行结束");
           
        });
}

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        }
        catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



标签:异步,int,future1,Override,CompletableFuture,Supplier,执行,public
来源: https://www.cnblogs.com/mznsndy/p/15899114.html