package com.sleep.demo.comp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolDemo {
private static final int THREAD_SIZE = Integer.parseInt(System.getProperty("getRealPriceInfo.THREAD_SIZE", "20"));
private static final long DEFAULT_TIMEOUT = Integer.parseInt(System.getProperty("getRealPriceInfo.defaultTimeout", "10000"));
private static final ThreadPoolExecutor REAL_PRICE_EXECUTOR = new ThreadPoolExecutor(
THREAD_SIZE, THREAD_SIZE, 30, TimeUnit.MINUTES, new LinkedBlockingDeque<>(), 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("getRealPriceInfo-" + count.incrementAndGet());
return thread;
}
}, new ThreadPoolExecutor.CallerRunsPolicy());
public static void main(String[] args) {
Integer pre=1;
Integer num=1;
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
CompletableFuture<Boolean> booleanCompletableFuture = CompletableFuture.supplyAsync(() -> {
try {
Tk tk = new Tk();
tk.call(pre, num);
return true;
} catch (Exception e) {
return false;
}
}, REAL_PRICE_EXECUTOR);
futures.add(booleanCompletableFuture);
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.get(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println("超时异常");
}
//获取返回结果
for (CompletableFuture<Boolean> future : futures) {
Boolean now = future.getNow(null);
System.out.println("result:"+now);
}
System.out.println("over"); } }