static class Task implements Callable<String>{
private int i=0;
public Task(int coun) {
i=coun;
}
@Override
public String call() throws Exception {
System.out.println("=======进入");
i++;
Thread.sleep(5000);
return "mytest---------"+i;
}
}
public static void main(String[] args) {
useFutureTest();
System.exit(0);;
}
private static void useFutureTest() {
int size=5;
ExecutorService executor=Executors.newFixedThreadPool(2);
CompletionService<String> completions=new ExecutorCompletionService<String>(executor);
for(int i=0;i<size;i++) {
completions.submit(new Task(i));
}
for(int i=0;i<size;i++) {
try {
System.out.println(completions.take().get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
当多线程执行需要返回执行结果的实现方式
最新推荐文章于 2022-12-12 17:17:52 发布