创建线程的另一种方式:实现Callable接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ceovip/article/details/82348797

在开发中,我们经常通过new thread或者实现runable接口的方式来创建线程,其实还可以通过实现Callable接口来创建线程。

先看一下API文档中关于Callable的介绍:
Callable

我们可以看出来,相较于实现Runnable接口的方式,实现Callable接口这种方法可以有返回值,并且可以抛出异常。

通过实现Callable接口来创建线程,需要依赖FutureTask实现类的支持,用于接收运算结果。

测试示例:

package com.li.test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 1.相较于实现Runnable接口的方式,方法可以有返回值,并且可以抛出异常
 * 2.需要依赖FutureTask实现类的支持,用于接收运算结果
 */

public class TestCallable {

    public static void main(String[] args) {
        CallableThreadTest ctt = new CallableThreadTest();
        FutureTask<Integer> result = new FutureTask<Integer>(ctt);

        new Thread(result).start();

        Integer sum;
        try {
            sum = result.get();
            System.out.println("-->" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class CallableThreadTest implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 100;
        System.out.println("CurrentThread-->" + Thread.currentThread());
        Thread.sleep(2000);
        return sum;
    }
}

在线程池中,一般和ExecutorService配合来使用。测试示例:

package com.li.test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestCallable {

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        System.out.println("主线程开始。。。" + Thread.currentThread());

        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> result = executor.submit(new CallableTask());
        executor.shutdown();
        Integer i = result.get();

        System.out.println("主线程结束。。。");
        System.out.println("主线程获取子线程结果为:" + i);
    }
}

class CallableTask implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 100;
        System.out.println("子线程开始计算。。。" + Thread.currentThread());

        Thread.sleep(3000);
        System.out.println("子线程结束计算。。。");
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/ceovip/article/details/82348797