线程池发送消息的队列功能!

luozhangwen 2010-04-26 11:59:18

package com.lzw.test;

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;

public class SendMsgThreadPool {
SendMsgThreadPoolManager sendMsgManager = SendMsgThreadPoolManager.INSTANCE;

public void sendMsg(String msg) {
sendMsgManager.addLogMsg(msg + "记录一条日志 ");
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new TestDriver().sendMsg(Integer.toString(i));
}
}

}
class SendMsgThreadPoolManager{
public static SendMsgThreadPoolManager INSTANCE = new SendMsgThreadPoolManager();
// 线程池维护线程的最少数量
private final static int POOL_MIN_SIZE = 4;
// 线程池维护线程的最大数量
private final static int POOL_MAX_SIZE = 10;
// 线程池维护线程所允许的空闲时间
private final static int POOL_KEEP_ALIVE_TIME = 0;
// 线程池所使用的缓冲队列大小
private final static int POOL_WORK_QUEUE_SIZE = 10;
// 消息缓冲队列
private Queue<String> msgQueue = new LinkedList<String>();
private SendMsgThreadPoolManager() {
}
private final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(((MsgToDBThread) r).getMsg() + "消息放入队列中重新等待执行");
msgQueue.offer(((MsgToDBThread) r).getMsg());
}
};

private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(POOL_MIN_SIZE, POOL_MAX_SIZE,
POOL_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(POOL_WORK_QUEUE_SIZE), this.handler);

// 访问消息缓存的调度线程
private final Runnable accessBufferThread = new Runnable(){
//查看是否有待定请求,如果有,则创建一个新的MsgToDBThread,并添加到线程池中
public void run() {
if(!msgQueue.isEmpty()){
String msg = msgQueue.poll();
Runnable task = new MsgToDBThread(msg);
threadPoolExecutor.execute(task);
}
}

};
// 调度线程池
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(accessBufferThread, 0, 1,TimeUnit.SECONDS);

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

}
class MsgToDBThread implements Runnable {
private String msg;

public MsgToDBThread(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}

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

public void run() {
//记录发送日志
System.out.println("记录发送日志 " + msg + " 到数据库中...!");
}
}

...全文
195 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧