设为首页 - 加入收藏 焦点技术网
热搜:java
当前位置:首页 >

线程池1

2011-11-23 22:18:00.0 null 任务 工作 class thread import  
导读:1.package com.demo2;import java.util.Collections;import java.util.LinkedList;import java.util.List;/** * @author Administrator * 线程池管理 */public class ThreadManager { public static final int SYSTEM_BUS...。。。
1.

package com.demo2;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Administrator
 * 线程池管理
 */
public class ThreadManager {

 public static final int SYSTEM_BUSY_TASK_COUNT = 150;

 // 默认池中的线程数
 private static int worker_num=5;
 
 // 已经处理的任务数
 private static int taskCounter =0;
 private List queue = Collections.synchronizedList(new LinkedList())

 // 系统是繁忙的吗。
 private boolean systemIsbusy =false;
  /* 单例 */
    private static ThreadManager instance ;

 // 池中的工作线程。
 public PoolWorker[] workers;
 
 
   private ThreadManager() {
         workers = new PoolWorker[5];
         for (int i = 0; i < workers.length; i++) {
             workers[i] = new PoolWorker(i);
         }
     }

     private ThreadManager(int pool_worker_num) {
         workers = new PoolWorker[pool_worker_num];
         for (int i = 0; i < workers.length; i++) {
             workers[i] = new PoolWorker(i);
         }
     }

     public static synchronized ThreadManager getInstance() {
         if (instance == null)
             return new ThreadManager();
         return instance;
     }

 
     /**
      * 销毁线程池
      */
      public synchronized void destroy() {
          for (int i = 0; i < worker_num; i++) {
              workers[i].stopWorker();
              workers[i] = null;
          }
          queue.clear();
      }

 private class PoolWorker extends Thread
 {
  
  private int index =-1;
  
  // 该工作线程是否有效
     private boolean isRunning=true;
    
     // 该工作线程是否可以执行新任务。
     private boolean isWaiting =true;
      
     public PoolWorker(int index)
     {
      this.index =index;
      start();
     }
     public void stopWorker()
     {
      this.isRunning =false;
     }
     public boolean isWaiting()
     {
      return this.isWaiting;
     }
    
   /**
    * 循环执行任务,
    * 这也许是线程池的关键所在。
    */
    
     @Override
     public void run()
     {
    
      while(isRunning)
      {
       Task r =null;
       synchronized (queue)
       {
    while(queue.isEmpty())
    {
     try {
      queue.wait(20);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    // 取出任务执行
    r=(Task)queue.remove(0);
    }
       if(r!=null)
       {
        isWaiting=false;
        r.run();
       }
      
       isWaiting = true;
             r = null;
      }
     }
 }
 
}

(编辑: xcw931924821)

网友评论