Callable和Future

// 創建一個線程
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws InterruptedException {
                Thread.sleep(1000);
                return "success";
            }
        });
        System.out.println(future.get());
        //創建十個線程
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool);
        for (int i = 0; i < 10; i++) {
            final int sq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(1000));
                    return sq;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(completionService.take().get());
        }

Callable 和Runable最大的區別就是Callable是有返回值的,用線程池ExecutorService創建線程的時候,不妨把這個線程池交給ExecutorCompletionService類來處理。可以將返回值用list來封裝。

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