Callable具有返回值,抛出异常。

import java.util.concurrent.Callable;

public class TestCallable implements Callable {
    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i < 5; i++) {
            System.out.println("Callable = " + i);
        }
        return true;
    }
    public static void main(String args[]) throws ExecutionException, InterruptedException             {
        TestCallable testCallable = new TestCallable();

        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> r1 = executorService.submit(testCallable);
        //获取结果
        boolean r11 = r1.get();
        //关闭服务
        executorService.shutdown();
    }
}

运行结果

更多推荐

Java基础:Callable