Callable接口像是Runnable接口的增强版,可以通过call()方法作为线程的执行体,但是call()方法比run()方法功能更加强大:有返回值,可以声明异常。java5提供了Future接口来获得线程执行体Call()方法的返回值,并可以控制它关联的Callable对象。
public class ThirdThread { public static void main(String[] args) { FutureTask<Integer> task = new FutureTask<Integer>( (Callable<Integer>) () -> { int i = 0; for (; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " : " + i); } return i; }); for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " : " + i); if (i == 20) { new Thread(task, "Thread with return").start(); } } try { System.out.println("The returned value of sub thread is:" + task.get()); } catch (Exception e) { e.printStackTrace(); } } }
值得注意的是:上面FutureTask对象的get()方法将导致主线程被阻塞,必须要call()方法结束并返回为止。另一个重载方法get(long timeout, TimeUnit unit)则是等待指定时间没有返回值则抛出TimeoutException。