使用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;

  }

  private ThreadPoolManager(){}

  private boolean hasMoreAcquire()

  {

  return !msgQueue.isEmpty();

  }

  public void addLogMsg( String msg )

  {

  Runnable task = new AccessDBThread( msg );

  threadPool.execute( task );

  }

  }

  public class AccessDBThread implements Runnable

  {

  private String msg;

  public String getMsg()

  {

  return msg;

  }

  public void setMsg( String msg )

  {

  this.msg = msg;

  }

  public AccessDBThread(){

  super();

  }

  public AccessDBThread(String msg){

  this.msg = msg;

  }

  public void run()

  {

  // 向數據庫中添加Msg變量值

  System.out.println("Added the message: "+msg+" into the Database");

  }

  }

  public class TestDriver

  {

  ThreadPoolManager tpm = ThreadPoolManager.newInstance();

  public void sendMsg( String msg )

  {

  tpm.addLogMsg( msg + "記錄一條日誌 " );

  }

  public static void main( String[] args )

  {

  for( int i = 0; i <100; i++ )

  {

  new TestDriver().sendMsg( Integer.toString( i ) );

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章