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))); //执行线程并添加返回值
}
for(