Executors創建線程池
newFixedThreadPool的阻塞隊列大小是沒有大小限制的,如果隊列堆積數據太多會造成資源消耗。
newCachedThreadPool是線程數量是沒有大小限制的,當新的線程來了直接創建,同樣會造成資源消耗殆盡。
ExecutorService executor = Executors.newFixedThreadPool(1);
CompletableFuture<String> future = CompletableFuture.supplyAsync( new Supplier<String>() {
@SneakyThrows
@Override
public String get() {
log.info(" resourceCategory is 2 , save order_resource_rt started!");
Thread.sleep( 3000l );
try {
//邏輯代碼
} catch (Exception e) {
e.printStackTrace();
}
return "save order_resource_rt ["+num+"] finished!";
}
}, executor);
//回調
future.thenAccept(e -> log.info(e + " ok"));
ThreadPoolExecutor創建線程池(推薦)
在新建線程池的時候使用ThreadPoolExecutor創建,阻塞隊列可以使用ArrayBlockingQueue,這個隊列的源碼很金典,鎖是一個成員變量。
開發中常用util
public class ThreadExecutorUtil {
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "cdb-c-" + poolNumber.getAndIncrement();
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
private static final Logger log = LoggerFactory.getLogger(ThreadExecutorUtil.class);
private int maxThreadNum = 10;
private ThreadPoolExecutor executor = new ThreadPoolExecutor(
this.maxThreadNum / 2 > 0 ? this.maxThreadNum / 2 : 1, //線程池默認線程數
this.maxThreadNum, //最大同時線程數
60L, //線程池維護線程所允許的空閒時間
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(32), //線程池所使用的緩衝隊列
new DefaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t != null) {
log.error("線程池內任務出錯:", t);
}
}
};
private static ThreadExecutorUtil instance = new ThreadExecutorUtil();
private ThreadExecutorUtil() {
}
public static void execute(Runnable runnable) {
log.debug("Active thread:" + instance.executor.getActiveCount()
+ ",wait threads:" + instance.executor.getQueue().size()
+ ",largest wait:" + instance.executor.getLargestPoolSize()
+ ",complete:" + instance.executor.getCompletedTaskCount());
instance.executor.execute(runnable);
}
}
調用代碼
ThreadExecutorUtil.execute(new Runnable() {
@Override
public void run() {
System.out.println("我是子線程");
}
});