目的:可以按线程池中线程执行完成的顺序拿到结果
package com.example.app;
import java.util.Random;
import java.util.concurrent.*;
public class CompletionServiceTest {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 4, 60, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(10));
CompletionService<Integer> completionService = new ExecutorCompletionService(threadPoolExecutor);
for(int i=0 ; i< 10 ; i++){
int finalValue=i;
completionService.submit( () -> {
Thread.sleep(new Random().nextInt(1000));
System.out.println(Thread.currentThread().getName());
return 1000+finalValue;
});
}
for(int i=0;i<10; i ++){
int result = completionService.take().get();
System.out.println(result);
}
threadPoolExecutor.shutdown();
}
}