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

在上一篇文章中使用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()方法的异常只能在内部消化,不能继续上抛;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值