Java 5.0 在 java.util.concurrent 提供了一个新的创建执行线程的方式:Callable 接口
Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常。Callable 需要依赖FutureTask ,FutureTask 也可以用作闭锁。例子:
package com.company;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;/** * Created by MSI1 on 2017/3/30. */public class TestCallableDemo { public static void main(String[] args) { try { DemoThread demoThread = new DemoThread(); FutureTaskintegerFutureTask = new FutureTask<>(demoThread); new Thread(integerFutureTask).start(); Integer result = integerFutureTask.get(); System.out.println("result = " + result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }}class DemoThread implements Callable { @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i <= 100; i++) { sum = sum + i; } return sum; }}
結果:
result = 5050