Callable接口

  Callable接口是一个与Runnable接口非常相似的接口。Callable接口的主要特征如下:

    接口。有简单类型参数,与call()方法的返回类型相对应。

    声明了call()方法。执行器运行任务时,该方法会被执行器执行。它必须返回声明中指定类型的对象。

    call()方法可以抛出任何一种校验异常。可以实现自己的执行器并重载afterExecute()方法来处理这些异常。

public class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("线程:"+Thread.currentThread().getName()+"实现Runnable接口");
    }

  public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(myCallable);
        new Thread(futureTask).start();
        String result = futureTask.get();
        System.out.println(result);

//        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,5,1, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10)){
//            @Override
//            protected void afterExecute(Runnable r, Throwable t) {
//                super.afterExecute(r, t);
//            }
//        };
//        Future<String> future = executor.submit(myCallable);
//        String res = future.get();
//        System.out.println(res);
//        executor.shutdown();
    }
}