package com.sleep.demo; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; public class MyTest { private static final ThreadPoolExecutor PRODUCT_EXECUTOR = new ThreadPoolExecutor( 2, 2, 30, TimeUnit.MINUTES, new SynchronousQueue<>(), new ThreadFactory() { private final AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setPriority(Thread.NORM_PRIORITY); thread.setName("CommonProductVoConverter-" + count.incrementAndGet()); return thread; } }, new ThreadPoolExecutor.CallerRunsPolicy()); public static void main(String[] args) { List<Long> productAlls = new ArrayList<>(); productAlls.add(1L); productAlls.add(5L); productAlls.add(2L); productAlls.add(3L); productAlls.add(4L); Random random = new Random(); List<CompletableFuture<String>> futures = productAlls.stream() .map(each -> CompletableFuture.supplyAsync(() -> { try { long i = random.nextInt(1000); System.out.println("random:"+i); Thread.sleep(i); return each+""; } catch (Exception e) { System.out.println("convert product error"+ e); // Profiler.businessAlarm("CommonProductVOConverter#convert", "convert product error: " + JsonUtils.toJson(each.getProduct())); return null; } }, PRODUCT_EXECUTOR)) .collect(Collectors.toList()); try { CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0])) .get(1, TimeUnit.SECONDS);
//CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(1 , TimeUnit.SECONDS); } catch (Exception e) { throw new RuntimeException("thread pool execute timeout", e); } for (CompletableFuture<String> future : futures) { String now = future.getNow(null); System.out.println("result:"+now); } } }
标签:productAlls,thread,jdk,1.8,util,CompletableFuture,import,new,多线程 From: https://www.cnblogs.com/niun/p/17000360.html