package com.sky.test;
import java.util.concurrent.*;
/**
* 線程池測試
* @author QZJ on 2018/10/28.
*/
public class ThreadPoolTest {
public static void main(String[] args) {
testThreadPool();
// testNormalThreadPool();
}
private static void testThreadPool() {
//ThreadPoolExecutor 說明
//corePoolSize: 當任務條數 <= corePoolSize,建立線程
//workQueue: 總任務數, 若目前線程數完全可以處理workQueue的任務,則workQueue隊列不會滿。
//maximumPoolSize: 當workQueue隊列滿時,并且 maximumPoolSize > 當任務條數 >= corePoolSize, 建立新的線程
//keepAliveTime: 當有空閑線程,超過aliveTime,回收
//allowCoreThreadTimeOut: 設定為true,這表示corePoolSize中的線程,在空閑時也可回收
//RejectedExecutionHandler: 添加任務,進行資源判斷,能否接受任務(既滿足以上條件),不能則抛出RejectedExecutionException異常
//tip: 當抛出RejectedExecutionException異常, 線程池仍處于可用狀态,并未shutdown,視情況是否需要捕獲異常
//tip: 最好自己建立ThreadFactory,确定目前執行的是哪一條線程
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,10, 1, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), Executors.defaultThreadFactory());
while (true) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("---------"+threadPoolExecutor.getQueue().size()+","+threadPoolExecutor.getTaskCount());
if (threadPoolExecutor.getQueue().size() == 0) {
for (int i=0;i<20;i++) {
try {
threadPoolExecutor.execute(new MyRunnable(i+"ThreadPoolExecutor******"));
} catch (Exception e) {
System.out.println("exception->"+i+"ThreadPoolExecutor******");
}
}
}
}
}
private static void testNormalThreadPool(){
//線程建立底層均使用的ThreadPoolExecutor
//定時執行 + 線程池
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> System.out.println("scheduledThreadPoolExecutor"), 0, 1, TimeUnit.SECONDS);
scheduledThreadPoolExecutor.shutdown();
//固定線程數
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
for (int i=0;i<12;i++) {
newFixedThreadPool.execute(new MyRunnable(i+"msg"));
}
newFixedThreadPool.shutdown();
//單例線程 單線程
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i=0;i<12;i++) {
newSingleThreadExecutor.execute(new MyRunnable("qzj"+i));
}
newSingleThreadExecutor.shutdown();
//可緩存線程池 無限制,較靈活
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
newCachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("newCachedThreadPool");
}
});
}
public static class MyRunnable implements Runnable {
private String msg;
public MyRunnable(String msg) {
this.msg = msg;
}
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(msg);
}
}
}