0%

Java 多线程编程 线程执行完的返回值

如果使用Runnable接口,run方法是没有返回值的,若需要返回值,可以使用Callable接口。不过在获取返回值时,如果线程没执行会,会阻塞。 代码来自Think in Java. TaskWithResult.java

package com.test;

import java.util.concurrent.Callable;

public class TaskWithResult implements Callable {
    private int id;
    public TaskWithResult(int id) {
        // TODO 自动生成的构造函数存根
        this.id=id;
    }

    @Override
    public String call() throws Exception {
        // TODO 自动生成的方法存根
        for(int i=0;i<5;i++)
        {
            System.out.println("#"+id+" "+i);
            Thread.sleep(1000);
        }
        return "result of TaskWithResult "+id;
    }

}



public class Main {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        //必须调用exec.submit方法开启线程,exec.submit会产生一个Feture对象
        ArrayList> results = new ArrayList>();
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
        }
        for (Future fs : results) {
            try {
                //fs,get()方法获取call方法的返回值,但如果调用时,call()方法没执行完,会阻塞
                //可以用fs.isDone()判断是否执行完
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } finally {
                exec.shutdown();
            }
        }

    }

}

说实话,不太理解为什么在finally里shutdown,而不是在第一个或者第二个for循环完。