异步执行

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();
        }
    }



上一篇:深圳黑马JavaEE第104期基础班+就业班+高手课件(笔记))


下一篇:图书管理系统(ssm框架) —— 02数据库连接