線程池使用:
ThreadFactory namedThreadFactory =?new?ThreadFactoryBuilder()
.setNameFormat("pool-%d").build();
ThreadPoolExecutor execServiceChores =?new?ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,?TimeUnit.MILLISECONDS,new SynchronousQueue(),
?namedThreadFactory, new?ThreadPoolExecutor.CallerRunsPolicy());
setNameFormat("名字"):給線程池設(shè)置名字
corePoolSize:核心線程數(shù)
maximumPoolSize:最大線程數(shù)
keepAliveTime:當(dāng)線程池里面線程沒有任務(wù)保持活躍時間
TimeUnit:時間單位
SynchronousQueue:線程池使用隊列類型
ArrayBlockingQueue數(shù)組形式存儲容量固定
SynchronousQueue沒有容量
LinkedBlockingQueue鏈表形式存儲容量固定
PriorityBlockingQueue二叉堆實現(xiàn)的優(yōu)先級阻塞隊列
ThreadPoolExecutor.CallerRunsPolicy():線程池使用策略
AbortPolicy當(dāng)線程池任務(wù)數(shù)量達(dá)到上限終止添加任務(wù)
CallerRunsPolicy重試添加當(dāng)前的任務(wù),他會自動重復(fù)調(diào)用execute()方法?
DiscardOldestPolicy拋棄舊的任務(wù)?
DiscardPolicy拋棄當(dāng)前的任務(wù)?
線程池關(guān)閉
pool.shutdown();?
try {?
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks?
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
System.err.println("Pool did not terminate");
}
}
} catch (InterruptedException ie) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
線程池定時任務(wù)使用
使用ScheduledExecutorService替代Timer,應(yīng)為Timer執(zhí)行任務(wù)中如果出現(xiàn)異常任務(wù)不執(zhí)行,ScheduledExecutorService出現(xiàn)異常任務(wù)繼續(xù)執(zhí)行
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor()长酗;
scheduler.scheduleAtFixedRate(() -> {"執(zhí)行任務(wù)"},
initialDelay,period,unit);
)
initialDelay等待多長時間執(zhí)行
period執(zhí)行任務(wù)周期
unit時間單位