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();
}