分享

Java实现的线程池、消息队列功能方法

 滚滚小白 2011-05-24

Java实现的线程池、消息队列功能方法

作者: 佚名,  出处:IT专家网, 责任编辑: 谢妍妍, 
2010-02-26 07:00
  本文介绍Java实现的线程池、消息队列功能方法。

  ThreadPoolManager类:负责管理线程池,调用轮询的线程来访问字符串缓冲区的内容,维护缓冲区,当线程池溢出时抛出的Runnable任务被加入到字符缓冲区。


 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 msgQueue = new LinkedList();
  // 访问消息缓存的调度线程
  final Runnable accessBufferThread = new Runnable()
  {
  public void run()
  {
  // 查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中
  if( hasMoreAcquire() )
  {
  String msg = ( String ) msgQueue.poll();
  Runnable task = new AccessDBThread( msg );
  threadPool.execute( task );
  }
  }
  };
  final RejectedExecutionHandler handler = new RejectedExecutionHandler()
  {
  public void rejectedExecution( Runnable r, ThreadPoolExecutor executor )
  {
  System.out.println(((AccessDBThread )r).getMsg()+"消息放入队列中重新等待执行");
  msgQueue.offer((( AccessDBThread ) r ).getMsg() );
  }
  };
  // 管理数据库访问的线程池
  final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
  CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
  new ArrayBlockingQueue( WORK_QUEUE_SIZE ), this.handler );
  // 调度线程池
  final ScheduledExecutorService scheduler = Executors
  .newScheduledThreadPool( 1 );
  final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(
  accessBufferThread, 0, 1, TimeUnit.SECONDS );
  public static ThreadPoolManager newInstance()
  {
  return tpm;
  }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多