java线程池和消息队列的运行流程分析

1.通过以下代码,向线程池中不断的放入线程任务
public static void main(String[] args) {
for(int i=0;i<100;i++){
new TestDriver().sendMsg( Integer.toString( i ) );
}
//new TestDriver().sendMsg(“发起一条对象” );
}

public void sendMsg( String msg ) {

  tpm.addLogMsg( msg + "记录一条日志 " );

}

2:addLogMsg()方法,创建一个线程任务,交给线程池去执行
public void addLogMsg(String msg) {
//将一个线程任务交给线程池去执行
Runnable task = new AccessDBThread(msg);
threadPool.execute(task);
}

3.线程池调用AccessDBThread类的run方法。

4.若加入的任务过多。超过了线程池的服务容量,则看线程池的服务拒绝策略是什么样的。
// 管理数据库访问的线程池
@SuppressWarnings({ “rawtypes”, “unchecked” })
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new ArrayBlockingQueue(WORK_QUEUE_SIZE), this.handler);

5.自定义的服务拒绝策略:将任务信息放入消息队列中
//一个没有能够被线程池执行的消息,重新放入消息队列中
//A handler for tasks that cannot be executed by a ThreadPoolExecutor.
final RejectedExecutionHandler handler = new RejectedExecutionHandler() {

    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        System.out.println(((AccessDBThread) r).getMsg() + "消息放入队列中重新等待执行");
        //将未能处理的消息放入消息缓冲队列中
        msgQueue.offer(((AccessDBThread) r).getMsg());
    }
};

6.定义一个定时执行的调度线程,定时的去调用一个实现了RUNNABLE接口的方法:accessBufferThread,
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(100);
@SuppressWarnings(“rawtypes”)
final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(accessBufferThread, 0, 1, TimeUnit.SECONDS);

7.检查消息队列是否为空,不为空则将消息取出,交给线程池去处理
// 访问消息缓存的调度线程
// 查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中
final Runnable accessBufferThread = new Runnable() {

    @Override
    public void run() {
        if (hasMoreAcquire()) {
            //取出消息队列的头一个信息
            String msg = (String) msgQueue.poll();
            //新建任务线程,将消息放入该线程中
            Runnable task = new AccessDBThread(msg);
            //将线程给线程池执行
            threadPool.execute(task);
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值