Java线程-线程池-带返回值

Java5之前,线程是没有返回值的。Java5之后,可以写有返回值的任务了。
有返回值的任务必须实现Callable接口,没有返回值的任务实现Runnable接口。
执行Callable接口后,可以获得一个Future的一个对象,通过Feture的get方法就能获得返回的Object数据了。
代码如下:

public class ThreadExtend_Pool_Return_Value {

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        //创建一个线程池
        ExecutorService executorService= Executors.newFixedThreadPool(2);
        //创建有两个返回值的线程
        Callable callable1=new CallableImpl("callable1");
        Callable callable2=new CallableImpl("callable2");
        //执行任务并获取future对象
        Future future1=executorService.submit(callable1);
        Future future2=executorService.submit(callable2);
        //从future获取返回值,并输出到控制台
        System.out.println(">>>>"+future1.get().toString());
        System.out.println(">>>>"+future2.get().toString());
        //关闭线程池
        executorService.shutdown();
    }
}
/**
 * 有返回值的线程需要实现Callable接口
 */
class CallableImpl implements Callable{
    private String oid;
    CallableImpl(String oid){
        this.oid=oid;
    }
    @Override
    public Object call(){
        return this.oid+"任务返回的内容";
    }
}

运行后,结果如下:

>>>>callable1任务返回的内容
>>>>callable2任务返回的内容

猜你喜欢

转载自blog.csdn.net/qq_24630433/article/details/88414588