ThreadPoolManager

本文介绍了一个线程池管理器的设计与实现,该管理器能够处理超出线程池容量的任务,通过将任务放入消息队列等待后续执行。此外,还包含了一个定期检查消息队列并尝试再次执行队列中任务的调度线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.neusoft.msqueue;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @desc 负责管理线程池,调用轮询的线程来访问字符串缓冲区的内容,维护缓冲区,当线程池溢出时抛出的Runnable任务被加入到字符缓冲区。
 *
 * @author anxh
 *
 */
public class ThreadPoolManager {

    private static ThreadPoolManager tpm = new ThreadPoolManager();

    // 线程池维护线程的最少数量
    private final static int CORE_POOL_SIZE = 4;

    // 线程池维护线程的最大数量
    private final static int MAX_POOL_SIZE = 10;

    // 线程池维护线程所允许的空闲时间
    private final static int KEEP_ALIVE_TIME = 0;

    // 线程池所使用的缓冲队列大小
    private final static int WORK_QUEUE_SIZE = 10;

    // 消息缓冲队列
    Queue<String> msgQueue = new LinkedList<String>();

    private ThreadPoolManager() {
    }

    public static ThreadPoolManager newInstance() {
        return tpm;
    }

    // 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序
    final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println(((AccessDBThread) r).getMsg() + "消息放入队列中重新等待执行");
            msgQueue.offer(((AccessDBThread) r).getMsg());
        }
    };

    /**
     * 管理数据库访问的线程池
     *
     * @param corePoolSize
     *            - 池中所保存的线程数,包括空闲线程。
     * @param maximumPoolSize
     *            - 池中允许的最大线程数。
     * @param keepAliveTime
     *            - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
     * @param unit
     *            - keepAliveTime 参数的时间单位。
     * @param workQueue
     *            - 执行前用于保持任务的队列。此队列仅由保持 execute 方法提交的 Runnable 任务。
     * @param handler
     *            - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。
     */
    final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(WORK_QUEUE_SIZE), this.handler);

    // 访问消息缓存的调度线程
    final Runnable accessBufferThread = new Runnable() {
        public void run() {
            // 查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中
            if (hasMoreAcquire()) {
                String msg = (String) msgQueue.poll();
                System.out.println("Poll the message: " + msg);
                Runnable task = new AccessDBThread(msg);
                threadPool.execute(task);
            }
        }
    };

    // 调度线程池
    final ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(1);

    // 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在
    // initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。
    final ScheduledFuture<?> taskHandler = scheduler.scheduleAtFixedRate(
            accessBufferThread, 0, 1, TimeUnit.SECONDS);

    private boolean hasMoreAcquire() {
        return !msgQueue.isEmpty();
    }

    public void addLogMsg(String msg) {
        Runnable task = new AccessDBThread(msg);
        threadPool.execute(task);
    }

}

class AccessDBThread implements Runnable {

    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public AccessDBThread() {
        super();
    }

    public AccessDBThread(String msg) {
        this.msg = msg;
    }

    public void run() {
        // 向数据库中添加Msg变量值
        System.out.println("Add the message: " + msg);
    }

}


package com.neusoft.msqueue;

public class Test {

    ThreadPoolManager tpm = ThreadPoolManager.newInstance();

    public Test() {
    }

    public void sendMsg(String msg) {
        tpm.addLogMsg(msg);
    }

    public static void main(String[] args) {

        for (int i = 0; i < 100; i++) {
            new Test().sendMsg(Integer.toString(i));
        }
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值