2 csdnzlw csdnzlw 于 2016.03.29 17:33 提问

java 多线程返回list对象

实现接口Callable,能给个例子吗?要求返回ArrayList();对象

2个回答

danielinbiti
danielinbiti   Ds   Rxr 2016.03.29 17:54
 public class Test2 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<ArrayList> result = executor.submit(task);
        executor.shutdown();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}
class Task implements Callable<ArrayList>{
    @Override
    public ArrayList call() throws Exception {
        System.out.println("子线程在进行计算");
        Thread.sleep(3000);

        return new ArrayList();
    }
}
wojiushiwo945you
wojiushiwo945you   Ds   Rxr 2016.03.29 17:57

主要理解Callable是和FutureTask一起使用,表示异步任务的。

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

/**
 * Callable是需要和FutureTask一起使用的,它表示异步任务
 * FutureTask的get()方法会被阻塞,直到Callable有数据返回
 *
 */
public class CallableThread {
    @SuppressWarnings("rawtypes")
    private final FutureTask<List> future = new FutureTask<List>(new CallableTask());

    private final Thread thread = new Thread(future);

    public void start(){
        thread.start();
        try {
            List<String> ret =future.get();

            //获取回调返回的结果
            if(ret!=null){
                System.out.println(ret);
            }
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new CallableThread().start();
    }
}

class CallableTask implements Callable<List>{

    @Override
    public List<String> call() throws Exception {
        List<String> ret = new ArrayList<String>();
        ret.add("hello");
        ret.add("world");
        ret.add("I");
        return ret;
    }

}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!