執行緒池引數及執行順序詳解ExecutorService
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
/**
* corePoolSize:執行緒池核心執行緒數,也是初始化執行緒數,優先使用corePoolSize。
* keepAliveTime:執行緒空閒達到空閒時間回收到執行緒池。
* BlockingQueue:當corePoolSize用完,先進佇列,此時maximumPoolSize沒有用
* maximumPoolSize:佇列滿了,且執行執行緒數小於最大執行緒數,建立新的執行緒
*
* BlockingQueue:核心執行緒用完,佇列滿了,做大執行緒數建立到了,再有新的任務過來,這時候採用拒絕策略,
* 拒絕策略:1.預設丟擲異常AbortPolicy;2.DiscardPolicy拒絕任務不拋異常,3.DiscardOldestPolicy彈出最先的新增進去
*
* @since 1.0
*/
public class ExecutorTest {
private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("adsytfs-pool-%d").build();
private static ExecutorService pool = new ThreadPoolExecutor(2, 3, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)
, namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
//任務1
pool.execute(new Runnable() {
@Override
public void run() {
try {
//主執行緒睡2秒
Thread.sleep(2 * 1000);
System.out.println("-------------helloworld_001---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//任務2
pool.execute(new Runnable() {
@Override
public void run() {
try {
//主執行緒睡5秒
Thread.sleep(5 * 1000);
System.out.println("-------------helloworld_002---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任務3
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_003---------------" + Thread.currentThread().getName());
}
});
// 任務4
pool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2 * 1000);
System.out.println("-------------helloworld_004---------------" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 任務5
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------------helloworld_005---------------" + Thread.currentThread().getName());
}
});
}
}