首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >java线程池创建

java线程池创建

原创
作者头像
时光_赌徒
修改2024-11-13 11:43:13
修改2024-11-13 11:43:13
1970
举报
文章被收录于专栏:记录记录
代码语言:javascript
复制
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.concurrent.*;

@Import({SpringUtil.class})
@Configuration
@Slf4j
public class ThreadPoolConfig {
 
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    @Bean(value = "executorService")
    public ThreadPoolExecutor threadPoolExecutor() {
        
        ThreadPoolExecutor executor = new TraceThreadPoolExecutor(
                CPU_COUNT,
                CPU_COUNT * 2 + 1,
                30L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(100000),
                Executors.defaultThreadFactory(),
                new BusinessAbortPolicy()) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                log.info("Thread ready to execute:{}", t.getName());
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                if (t == null) {
                    log.info("Thread execution complete:{}", new Thread(r).getName());
                } else {
                    log.error("Thread execution exception{}--->{}", new Thread(r).getName(), t.getMessage());
                }
            }

            @Override
            protected void terminated() {
                log.info("Thread pool exit");
            }
        };
        return executor;
    }
}

class BusinessAbortPolicy implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        Log log = Log.get();
        String message = "任务 " + r.toString() + " 被 " + executor.toString() + "拒绝!!";
        log.error("The_thread_pool_is_full and cannot continue processing tasks>>>>{}", message);
    }
}

class TraceThreadPoolExecutor extends ThreadPoolExecutor {

    public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
                                   RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    public void execute(Runnable command) {
        super.execute(wrap(command, clientTrace(), Thread.currentThread().getName()));
    }

    @Override
    public Future<?> submit(Runnable task) {
        return super.submit(wrap(task, clientTrace(), Thread.currentThread().getName()));
    }

    private Exception clientTrace() {
        return new Exception("============Client_thread_exception=================");
    }

    private Runnable wrap(final Runnable task, final Exception clientStack, String clientThreadName) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    task.run();
                } catch (Exception ex) {
                    clientStack.printStackTrace();
                    throw ex;
                }
            }
        };
    }

}
//使用
CompletableFuture.runAsync(() -> {
    doSomething
}, executorService);

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档