java多線程:Future與Callable詳解

1.Callable與Runnable的相同點與不同點是什麼?

答:Callable與Runnable接口都需要實現默認方法,Callable實現call()方法,Runnable實現run()方法,他們都能夠被線程池調用,但是call()有返回值,run()方法沒有返回值。

2.call()方法的返回值如何獲取?

答:通過Future的get()方法來獲取call()方法的返回值。

例子:

package com.springboot.thread.future_and_callable;

import java.util.concurrent.*;

public class TestCallable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,3,1L, TimeUnit.SECONDS,new LinkedBlockingDeque<>(),new ThreadPoolExecutor.CallerRunsPolicy());
        MyCallable myCallable = new MyCallable("zlb");
        Future<String> future = threadPoolExecutor.submit(myCallable);
        System.out.println(future.get());
        threadPoolExecutor.shutdown();
    }

}

class MyCallable implements Callable<String>{

    private String  name;

    public  MyCallable(String name){
        this.name = name;
    }

    @Override
    public String call() throws Exception {
        System.out.println("current thread is :"+Thread.currentThread().getName());
        //thread do sth.
        Thread.sleep(1000l);
        return "i am "+ name;
    }
}

 運行結果:

3.submit()方法不僅可以傳入Callable對象,也可以傳入Runnable對象。

 

4.execute()與submit()的區別?

答:(1).execute()方法沒有返回值,submit()方法有返回值

        (2).execute()方法默認情況下直接拋出異常,不能捕獲異常,要捕獲異常只能通過自定義線程工廠(ThreadFactory)來捕獲異常,而submit()可以直接用try-catch來獲取異常信息。

 

5.Future的缺點:

總結一下:他能提供返回值既是他的優點,也是他的缺點,優點就是能提供返回值,缺點就是如果你想要獲得返回值的話你必須要調用get()方法,而get()方法是阻塞的,會影響執行的效率。

 

 

 

 

 

 

 

 

 

 

 

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