java 线程池实例

 假如创建线程的时间开销为T1,线程执行任务的时间为T2,销毁线程的时间为T3,如果T1+T3 >> T2, 这个时候使用线程池往往能大大的提高性能.下面是个线程池的实例.
1. 任务接口Task

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package main;

  6. /**
  7.  *
  8.  * @author fuzuotao
  9.  */
  10. /* 所有任务的接口 */
  11.   public abstract class Task implements Runnable {
  12.         public long _taskID = 0;
  13.         public Task(){
  14.             
  15.         }
  16.         
  17.         public Task(long task_id){
  18.             _taskID = task_id;
  19.         }
  20.         
  21.         public void setTaskId(long task_id){
  22.             _taskID = task_id;
  23.         }
  24.         
  25.         public long getTaskId(){
  26.             return _taskID;
  27.         }
  28.         
  29.         public void run(){
  30.             System.out.printf("test\r\n");
  31.         }
  32.  }
2. 线程池ThreadPool

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package main;

  6. import java.util.LinkedList;
  7. import java.util.List;
  8. import java.util.Collections;
  9. import org.apache.log4j.Logger;

  10. /**
  11.  *
  12.  * @author fuzuotao
  13.  */
  14. public class ThreadPool{
  15.     public static long _next_task_id = 0;
  16.     public static final int DEFAULT_THREAD_NUM = 0xa;
  17.     public static final int MAX_THREAD_NUM = 200;
  18.     public int _cur_thread_num = 0;
  19.     public boolean _is_closed = true;
  20.     public List<Task> taskQueue = Collections.synchronizedList(new LinkedList<Task>());
  21.     public WorkThread[] threads;
  22.     
  23.     public static ThreadPool _instance = null;
  24.     
  25.     static Logger logger = Logger.getLogger(ThreadPool.class);
  26.     
  27.     public ThreadPool(){
  28.         _cur_thread_num = DEFAULT_THREAD_NUM;
  29.         threads = new WorkThread[_cur_thread_num];
  30.         for(int i = 0; i < _cur_thread_num; ++ i){
  31.             threads[i] = new WorkThread(i);
  32.         }
  33.     }
  34.     
  35.     public ThreadPool(int thread_num){
  36.         _cur_thread_num = thread_num;
  37.         threads = new WorkThread[_cur_thread_num];
  38.         for(int i = 0; i < _cur_thread_num; ++ i){
  39.             threads[i] = new WorkThread(i); 
  40.         }
  41.     }
  42.     
  43.     /* singleton */
  44.     public static ThreadPool getInstance(){
  45.         if(_instance == null){
  46.             synchronized(ThreadPool.class){
  47.                 if(_instance == null){
  48.                     _instance = new ThreadPool();
  49.                 }
  50.             }
  51.         }
  52.         return _instance;
  53.     }
  54.     
  55.     public static long generateTaskId(){
  56.         _next_task_id += (_next_task_id + 1) / 1000000;
  57.         if(_next_task_id == 0) _next_task_id ++;
  58.         return _next_task_id;
  59.     }
  60.     
  61.     public void start(){
  62.         _is_closed = false;
  63.         for(int i = 0; i < _cur_thread_num; ++ i){
  64.             threads[i].start();
  65.             logger.info(String.format("thread [%d] start!", i));
  66.         }
  67.     }
  68.     
  69.     public void close(){
  70.         if(!_is_closed){
  71.             waitforfinish();
  72.             _is_closed = true;
  73.             taskQueue.clear();
  74.         }
  75.         logger.info("Thread pool close!");
  76.     }
  77.     
  78.     public void waitforfinish(){
  79.         synchronized(this){
  80.             _is_closed = true;
  81.             notifyAll();
  82.         }
  83.         for(int i = 0; i < _cur_thread_num; ++ i){
  84.             threads[i].stopThread();
  85.             logger.info(String.format("Thread [%d] stop!", i));
  86.         }
  87.     }
  88.    
  89.     public void addTask(Task new_task){
  90.         if(_is_closed){
  91.             throw new IllegalStateException();
  92.         }
  93.         synchronized(taskQueue){
  94.             if(new_task != null){
  95.                 taskQueue.add(new_task);
  96.                 taskQueue.notifyAll();
  97.                 //taskQueue.notify();

  98.             }
  99.         }
  100.     }
  101.     
  102.     public int getTaskCount(){
  103.         return taskQueue.size();
  104.     }
  105.     
  106.     public class WorkThread extends Thread{
  107.         private int _index;
  108.         private boolean _is_running = true;
  109.         public WorkThread(int index){
  110.             _index = index;
  111.         }
  112.         
  113.         public void run(){
  114.             while(_is_running){
  115.                 Task t = getTask();
  116.                 if(!= null){
  117.                     t.run();
  118.                 }else{
  119.                     // 结束线程

  120.                     logger.info(String.format("thread [%d] exit", _index));
  121.                     return;
  122.                 }
  123.             }
  124.         }
  125.         
  126.         public Task getTask(){
  127.             if(_is_closed) return null;
  128.             Task r = null;
  129.             synchronized (taskQueue) {
  130.                 while (taskQueue.isEmpty()) {
  131.                     try {
  132.                         /* 任务队列为空,则等待有新任务加入从而被唤醒 */
  133.                         taskQueue.wait();
  134.                     } catch (InterruptedException ie) {
  135.                         logger.error(PrintStackTrace.getStackTrace(ie));
  136.                     }
  137.                 }
  138.                 
  139.                 /* 取出任务执行 */
  140.                 r = (Task) taskQueue.remove(0);
  141.                 return r;
  142.             }
  143.         }
  144.         
  145.         public void stopThread(){
  146.             _is_running = false;
  147.             try{
  148.                 join();
  149.             }catch(InterruptedException ex){
  150.                 logger.error(PrintStackTrace.getStackTrace(ex));
  151.             }
  152.         }
  153.     }
  154.     
  155. }
在实际使用过程中继承Task抽象类,并重写run()方法即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值