线程池代码

本文深入探讨Java线程池的使用,通过实例代码展示如何在应用程序中有效地管理和利用线程池,提升并发性能。
摘要由CSDN通过智能技术生成

线程池

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池工具类,工程所有多线程均调用此类,控制整个工程允许的最大线程数
 */
@Slf4j
public class ThreadPool {
    public static ThreadPool threadPool;
    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(30,
            new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());

    public static ThreadPool getInstance() {
        if (threadPool == null) {
            threadPool = new ThreadPool();
        }
        return threadPool;
    }

    public void run(Runnable r) {
        executorService.execute(r);
    }

    public void run(Runnable r, long initialDelay, long period, TimeUnit unit) {
        executorService.scheduleAtFixedRate(r, initialDelay, period, unit);
    }
}

使用方式:
在需要使用的地方添加

        ThreadPool.getInstance().run(() -> {
            System.out.println("使用线程池打印");
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值