多线程 - Callable、Future、FutureTask

传统Runnable没有返回值,所以引入Callable

public interface Callable<V> {
    V call() throws Exception;
}

调用采用ExecutorService调用

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

Future:结果返回类

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning); //取消任务,成功true;mayInterruptIfRunning是否取消正在运行的任务
    boolean isCancelled(); //是否被取消
    boolean isDone(); //是否完成
    V get() throws InterruptedException, ExecutionException; //获取结果,阻塞
    V get(long timeout, TimeUnit unit) //一定时间内获取结果
        throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask 实现Runnable和Future接口,可以直接用传统方式调用。将结果和Runnable相结合的一个结构体。
实现运用(Future)

public class CallableTest implements Callable {
    @Override
    public Object call() throws Exception {
        Thread.sleep(3000);
        return 0;
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        CallableTest callableTest = new CallableTest();
        Future<Object> future = executorService.submit(callableTest);
        executorService.shutdown();
        try {
            System.out.println("结果:");
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

实现运用(FutureTask)

public class CallableTest implements Callable {
    @Override
    public Object call()  {
        System.out.println("run");
//        Thread.sleep(3000);
        return 0;
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        CallableTest callableTest = new CallableTest();
        Future future = executorService.submit(callableTest);

        FutureTask<Object> futureTask = new FutureTask<Object>(callableTest);
        new Thread(futureTask).start();

        executorService.shutdown();
        try {
            System.out.println("结果:");
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值