java多线程学习——(2)通过Callable创建线程

来源:互联网 发布:云计算与大数据关系 编辑:程序博客网 时间:2024/06/05 06:04

在上一篇文章中使用Runnable和Thread两种方式创建线程,这样创建存在一个问题就是我没有办法取到线程返回结果也捕获不到线程运行时的异常。Callable接口的用法:

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Call{    public static void main(String[] args) throws Exception, Exception {        ExecutorService executorService=Executors.newFixedThreadPool(1);        NewThread newThread=new NewThread();        Future<Integer> future=executorService.submit(newThread);        int num=future.get();        System.out.println(num);        executorService.shutdown();    }}class NewThread implements Callable<Integer>{    @Override    public Integer call() throws Exception {        return 100;    }   }

通过这种方式我们能够获取到NewThread线程执行的返回值100。

Callable接口的源码:

public interface Callable<V> {    /**     * Computes a result, or throws an exception if unable to do so.     *     * @return computed result     * @throws Exception if unable to compute a result     */    V call() throws Exception;}

该接口中有且仅有一个call()方法,但是需要注意,该方法向上抛出一个Exception异常。


Runnable接口与Callable接口的区别:
1. 实现Callable接口的任务线程能返回执行结果;而实现Runnable接口的任务线程不能返回结果;
2. Callable接口的call()方法允许抛出异常;而Runnable接口的run()方法的异常只能在内部消化,不能继续上抛;

阅读全文
0 0
原创粉丝点击