Callable和Future创建线程

Callable和Future创建线程

Callable是一个接口,而且还是一个函数式接口
@FunctionalInterface
public interface Callable

在这里插入图片描述

该接口有一个call()方法,call方法和run方法是有区别的,最主要的区别是call方法是有返回值的,call返回会抛出异常的
在这里插入图片描述

future接口
Interface Future

在这里插入图片描述

我们先看看怎么创建线程

thread的构造方法
在这里插入图片描述
可以看出Thread的构造方法是没有Callable的,所以无法通过
new Thread(Callable)创建线程的。

看一看Runnable有哪些实现类
在这里插入图片描述
现在来看看FutureTask这个类
在这里插入图片描述
实现了Future和Runnable接口
在这里插入图片描述
在这里插入图片描述
通过这样层层的描述,那么我们就可以这样创建线程了

1.写一个类实现Callable接口,重写里面的call方法,比如这个类是T

2.创建一个FutureTask对象,比如 new FutureTask(T );

3.new Thread(new FutureTask(T ));

代码实现:

public class CallThreadTest {
    
    public static void main(String[] args) {
        CallThread t= new CallThread();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(t);
        Thread thread = new Thread(integerFutureTask);
        thread.start();
        try {
            //获取call方法返回的值,call方法会抛出异常,所以这里需要捕获一下
            Integer integer = integerFutureTask.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    static class CallThread implements Callable<Integer>{
        //重写call方法,call方法和run方法还有有几点区别的,最大的区别就是call方法有返回值
        @Override
        public Integer call() throws Exception {
            return 12345;
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值