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);
}
}
}
线程池 ThreadPoolExecutor 总结
最新推荐文章于 2023-04-24 00:00:00 发布