Callable 介绍

Callable 接口用来创建一个被线程执行的类,和 Runnable 类似,但又有区别。

使用示例

class MyThread implements Callable<String> {
    @Override
    public String call() throws Exception {
        for ( int x = 0 ; x < 10 ; x ++ ) {
            System.out.println("******线程执行,x = " + x);
        }
        return "线程执行完毕!";
    }
}

public class Test {
    public static void main(String[] args) throws Exception{
        FutureTask futureTask = new FutureTask(new MyThread());
        new Thread(futureTask).start();
        System.out.println("线程返回值:" + futureTask.get());
    }
}

Callable 源码

package java.util.concurrent;

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

Callable 和 Runnable 区别

1、Callable 规定的方法是 call(),而 Runnable 规定的方法是 run()。

2、Callable 的任务执行后可返回值,而 Runnable 的任务是不能返回值的。

3、call() 方法可抛出异常,而 run() 方法是不能抛出异常的。

相关文章: