1.简单介绍通过实现Callable接口创建线程
与Runable相比的区别在于:runable没有返回值,
Callable可以用Future<数据类型>接收返回值
class TaskWithResult implements Callable<String> { //创建一个线程
private int id;
public TaskWithResult(int id) {
this.id=id;
}
@Override
public String call() throws Exception {
return "result of TaskWithResult "+id;
}
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
public class CallableTest {
public static void main(String[] args) {
ExecutorService exec=Executors.newCachedThreadPool(); //创建线程池
List<Future<String>> results=new ArrayList<Future<String>>(); //定义接收返回值的list
for(int i=0;i<5;i++) {
results.add(exec.submit(new TaskWithResult(i))); //执行线程并添加返回值
}

本文介绍了如何使用Callable接口创建线程,对比了它与Runnable的不同,重点在于Callable能获取处理后的返回值。并展示了在多线程环境下,如何利用Callable处理List中的数据。
最低0.47元/天 解锁文章
2588

被折叠的 条评论
为什么被折叠?



