java多线程四:Callable接口解析

本文对比分析了Java中Callable和Runnable接口的区别,并介绍了如何使用Callable接口配合ExecutorService和Future接口来执行有返回值的任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Callable接口和Runnable接口

首先看一下Runnable接口的定义:

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

Runnable接口中仅仅定义了一个run()方法,返回值类型为void,当线程启动,任务执行完成后无法返回任何结果。

现在看一下Callable接口的定义:

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

Callable接口是一个泛型接口,定义了一个call()方法,返回类型为传递进来的泛型的具体类型。

比较分析:
1. Runnable接口和Callable接口都是定义任务,创建线程的实现方式
2. 两者的不同之处在于Callable接口有返回结果,而Runnbale接口没有返回值

示例:使用Callable接口定义一个任务

public class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    public String call() throws Exception {
        return "Result of TaskWithResult " + id;
    }
}

Future接口

那么怎么使用Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:

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

也就是说,定义好的Callable任务通过ExecutorService的submit()方法来调用,返回结果封装到Future中。

现在分析Future接口,该接口的定义非常简单:

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}

Future接口也是一个泛型接口,定义了一系列方法用来检测线程的状态或者获取线程的返回值

  • cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
  • isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。
  • isDone方法表示任务是否已经完成,若任务完成,则返回true。
  • get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回。
  • get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。

示例

public class CallableDemo01 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
        }
        for (Future<String> future : results) {
            if (future.isDone()) {
                System.out.println(future.get());
            } else {
                System.out.println("Future result is not yet complete");
            }
        }
    }
}

FutureTask类

FutureTask类是Future接口的唯一实现类。
示例:

public class CallableDemo02 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        executor.submit(futureTask);
        executor.shutdown();

        Thread.sleep(1000);

        System.out.println("主线程在执行任务");
        System.out.println("task运行结果" + futureTask.get());
        System.out.println("所有任务执行完毕");
    }
}

参考:
http://www.cnblogs.com/dolphin0520/p/3949310.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值