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()方法是阻塞的,会影响执行的效率。