一、通过实现callable创建带有返回值的线程
public class ThreadTest implements Callable {
private int count;
public ThreadTest(Integer count){
this.count = count;
}
@Override
public String call() throws Exception {
return "测试"+count;
}
}
二、测试方法
public class ThreadTests {
@Test
public void test1(){
//初始化线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<String>> list= new ArrayList<Future<String>>();//
for (int i = 0; i <10 ; i++) {
Callable threadTest = new ThreadTest(i);
try {
Future submit = executorService.submit(threadTest);
list.add(submit);
} catch (Exception e) {
e.printStackTrace();
}
}
//任务执行完成后关闭线程池
executorService.shutdown();
while(true){
//线程池中线程是否全部执行完毕
if(executorService.isTerminated()){
list.stream().forEach(future -> {
try {
//打印结果
System.out.println(future.get().toString());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
break;
}
}
}
}