Example of parallel service processing
- Defining a thread pool
final static AtomicLong idGen = new AtomicLong(0);
static ExecutorService executor = new ThreadPoolExecutor(3.3.30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new ThreadFactory() {
@Override
public Thread newThread(Runnable cmd) {
Thread t = new Thread(cmd);
t.setName("t-prd-" + idGen.incrementAndGet());
returnt; }});Copy the code
- Business processing simulation
private static String process(ProductCommon product) {
return "Current thread :" + Thread.currentThread().getName() + ", processing result test :" + product.getProductId();
}
Copy the code
- The core three lines of code are processed concurrently
List<ProductCommon> products = Lists.newArrayList(p1, p2, p3); List<CompletableFuture<String>> prdFutures = products.stream() .map(i -> CompletableFuture.supplyAsync(() -> process(i), executor)) .collect(Collectors.toList()); List<String> prdResults = prdFutures.stream().map(CompletableFuture::join).collect(Collectors.toList());Copy the code
- Results the print
Current thread: t-PRd -1, processing result test:1Current thread: t-PRd -2, processing result test:2Current thread: t-PRd -3, processing result test:3
Process finished with exit code 0
Copy the code