java 多线程返回list对象

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

2个回答

 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();
    }
}

主要理解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
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐