线程池和线程调度

1,线程池有一个缓冲队列(用来存储提交到线程池的线程任务,然后线程池就从这里面取出任务来执行):ArrayBlockingQueue
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS,new ArrayBlockingQueue( WORK_QUEUE_SIZE ), this.handler);

2,在线程池中,如果任务数量过多,有一个拒绝策略,其中一种是可以吧任务放入到另外一个消息缓冲队列中:msgQueue

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

final RejectedExecutionHandler handler = new RejectedExecutionHandler(){

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        System.out.println(((AccessDBThread )r).getMsg()+"消息放入队列中重新等待执行");
        msgQueue.offer((( AccessDBThread ) r ).getMsg() );
    }
};

3,预定执行:也就是线程池机制的timer的泛化
用它来作为类似定时器,定时的去执行将消息缓冲队列中的消息,放入到线程池中去执行

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

@SuppressWarnings("rawtypes")
final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(accessBufferThread, 0, 1, TimeUnit.SECONDS);

4,调度线程池要执行的方法:

// 访问消息缓存的调度线程
// 查看是否有待定请求,如果有,则创建一个新的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 );
        }
    }
};

5,查看消息缓冲队列中是否有消息
private boolean hasMoreAcquire(){
return !msgQueue.isEmpty();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值