首页 > 编程语言 > 详细

实现Callable接口来创建线程

时间:2020-03-15 00:23:59      阅读:67      评论:0      收藏:0      [点我收藏+]

使用Callable来创建线程,可以获得返回结果,并且可以抛出异常。

和Runnable的具体区别有:

1)Runnable重写的是run方法,Callable重写的是call方法。

2)Callable能够抛出exception,而Runnable不可以。

3)Callable能够得到返回结果,而Runnable不可以。

4)Callable和Runnable都可以应用于executors,而Thread类只支持Runnable。

借助线程池来实现:

public class TestCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.println("测试"+i);
        }
        return "运行结束";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //借助线程池来运行,创建执行服务
        ExecutorService exec = Executors.newCachedThreadPool();
        //提交执行
        Future<String> future = exec.submit(new TestCallable());
        //获得返回信息
        System.out.println(future.get());
        //关闭服务
        exec.shutdown();
    }
}

 借助FutureTask类来实现:

public class TestCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.println("测试"+i);
        }
        return "运行结束";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //开始线程
        FutureTask<String> futureTask = new FutureTask<>(new TestCallable());
        new Thread(futureTask).start();
        //通过futuretask可以得到MyCallableTask的call()的运行结果:
        System.out.println(futureTask.get());
    }
}

 

实现Callable接口来创建线程

原文:https://www.cnblogs.com/yamiya/p/12495320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!