话不都说,这里直接贴出代码:
package com.whb.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.whb.demo.Student;
public class FutureTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Future<Student>> results = new ArrayList<Future<Student>>();
ExecutorService es = Executors.newCachedThreadPool();
List<Student> list = new ArrayList<Student>();
for (int i = 0; i < 10; i++) {
Student stu = new Student();
stu.setAge(i);
stu.setName("张三"+i);
list.add(stu);
}
for (Student student : list) {
results.add(es.submit(new TaskStuCallable(student)));
}
for (Future<Student> res : results){
System.out.println(res.get().toString());
list.add(res.get());
}
}
public static class TaskStuCallable implements Callable<Student> {
private Student stu;
public TaskStuCallable(Student stu) {
super();
this.stu = stu;
}
@Override
public Student call() throws Exception {
String tid = String.valueOf(Thread.currentThread().getId());
System.out.printf("Thread#%s : in call\n", tid);
stu.setAge(Integer.valueOf(tid));
stu.setName(stu.getName()+"----"+tid);
return stu;
}
}
}
总结使用:此处使用的线程池是ExecutorService es = Executors.newCachedThreadPool();Future。但是也可以考虑使用
ExecutorService threadPool = Executors.newCachedThreadPool();
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
for(int i = 1; i < 5; i++) {
final int taskID = i;
cs.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return taskID;
}
});
}
for(int i = 1; i < 5; i++) {
try {
System.out.println(cs.take().get());
} catch (Exception e) {
e.printStackTrace();
}
}
CompletionService可以保证执行的顺便,但是Future好像也是可以保证顺序输出的。亲测如下:
Thread#10 : in call
Thread#19 : in call
Thread#18 : in call
Student [age=10, name=张三0----10]
Thread#17 : in call
Thread#16 : in call
Thread#15 : in call
Thread#14 : in call
Thread#13 : in call
Thread#12 : in call
Thread#11 : in call
Student [age=11, name=张三1----11]
Student [age=12, name=张三2----12]
Student [age=13, name=张三3----13]
Student [age=14, name=张三4----14]
Student [age=15, name=张三5----15]
Student [age=16, name=张三6----16]
Student [age=17, name=张三7----17]
Student [age=18, name=张三8----18]
Student [age=19, name=张三9----19]
好了,这是我本地测试的结果。