1 Callable类和Future接口介绍
JDK5开始,Java创建多线程的方法新增了Callable接口,源码如下:
public interface Callable<V> {
V call() throws Exception;
}
相对使用Runnable接口或实现Thread类来创建多线程,其具2大优点:
1)Runnable接口或实现Thread类的run()方法不能声明异常抛出;而Callable接口的call()方法可以声明异常抛出;
2)Runnable接口或实现Thread类的run()方法是void类型,没有返回值;而Callable接口的call()方法可以有返回值,通过Future接口的get()方法可以获得Callable接口的返回值。
2 测试用例
2.1异常测试用例
public class MyCallable implements Callable<String> {
private String name;
public MyCallable(String name) {
this.name = name;
}
@Override
public String call() throws Exception{ //声明异常
Thread.sleep(5000);
throw new InterruptedException(); //抛出异常
}
}
public class FutureApp1 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
MyCallable callable = new MyCallable("JayLai");
Future<String> future = executorService.submit(callable);
try {
//产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数
long time1 = System.currentTimeMillis();
System.out.println(future.get()); //get()方法是阻塞的
long time2 = System.currentTimeMillis();
System.out.println("阻塞时间为:" + (time2 - time1)+ "毫秒");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally{
System.out.println("====end=====");
}
}
}
测试结果:
2.2 返回值测试用例
public class MyCallable implements Callable<String> {
private String name;
public MyCallable(String name) {
this.name = name;
}
@Override
public String call() throws Exception{ //声明异常
Thread.sleep(5000);
return name;
}
}
public class FutureApp2{
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
MyCallable callable = new MyCallable("JayLai");
Future<String> future = executorService.submit(callable);
try {
//产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数
long time1 = System.currentTimeMillis();
System.out.println("用户名: " + future.get()); //get()方法是阻塞的
long time2 = System.currentTimeMillis();
System.out.println("阻塞时间为:" + (time2 - time1)+ "毫秒");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally{
System.out.println("====end=====");
}
}
}
测试结果:
3 参考文献
[1] 高洪岩, Java多线程编程核心技术. 2015.
[2] Goetz, B.等, Java 并发编程实战. 2012.
[3] https://docs.oracle.com/javase/8/docs/api/index.html