JUC之獲取子線程的執行結果Future和Callable

Runable的缺點:沒有返回值也不能拋出Checked Exception

Future的主要方法

get()
//get方法的行爲取決於Callable任務的狀態分五種情況

//1 任務正常完成,get立即返回結果

//2 任務尚未完成(未開始或進行中),get被阻塞直到任務完成

//3 任務被中斷,get返回InterruptedException

//4 任務被取消,get返回CancellationException

//5 任務執行異常,get返回ExecutionException

get(long timeout, TimeUnit unit) //TimeoutException

//如果線程沒有開始直接取消方法返回true.
//如果線程已完成或者已取消,返回false
//如果線程已經開始執行,那麼將會根據參數是否中斷執行的線程
boolean cancel(boolean mayInterruptIfRunning);

//是否完成,不管是否成功完成
boolean isDone();

線程池的submit方法返回Future

代碼示例



/**
 * 描述:     演示批量提交任務時,用List來批量接收結果
 */
public class MultiFutures {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(20);
        ArrayList<Future> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = service.submit(new CallableTask());
            futures.add(future);
        }
        Thread.sleep(5000);
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = futures.get(i);
            try {
                Integer integer = future.get();
                System.out.println(integer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    static class CallableTask implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            Thread.sleep(3000);
            return new Random().nextInt();
        }
    }
}

FuterTask獲取Future

代碼案例:



/**
 * 描述:     演示FutureTask的用法
 */
public class FutureTaskDemo {

    public static void main(String[] args) {
        Task task = new Task();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(task);
//        new Thread(integerFutureTask).start();
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(integerFutureTask);

        try {
            System.out.println("task運行結果:"+integerFutureTask.get());

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class Task implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("子線程正在計算");
        Thread.sleep(3000);
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum;
    }
}

 

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