且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 基于Callable接口的线程实例

更新时间:2022-08-17 22:48:37

1. 背景

之前已经实现了继承Thread的线程实例,也实现了基于Runnable接口的线程实例。

这两种方式实现的线程,都是有一个run()方法,但是没法设置返回值。

通过Callable接口,我们可以为线程设定返回值,然后可以等待获取返回值,非常好用。

2. 代码实现


/**
 * 读文件大小
 */
public class ReadFileCallable implements Callable<Long> {

    private String fileName;

    public ReadFileCallable(String fileName) {
        this.fileName = fileName;
    }

    /**
     * 计算文件大小并返回
     */
    @Override
    public Long call() throws Exception {
        File f = new File(fileName);
        if (f.exists() && f.isFile()) {
            return f.length();
        } else {
            return null;
        }
    }

    /**
     * 测试
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<Long> task = new FutureTask<Long>(new ReadFileCallable("D:\\temp\\501.txt"));
        Thread thread = new Thread(task);
        thread.start();
        System.out.println(task.get());// 等待结果返回
    }
}

3. 解析

注意Callable接口实现类还需要通过FutureTask包装下,才能借助线程Thread启动。

当执行task.get()时,当前线程会阻塞,直到call()方法执行完成。