Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1774293
  • 博文数量: 198
  • 博客积分: 4088
  • 博客等级: 上校
  • 技术积分: 2391
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-15 16:29
个人简介

游戏开发,系统架构; 博客迁移到:http://www.jianshu.com/u/3ac0504b3b8c

文章分类

全部博文(198)

文章存档

2017年(1)

2016年(12)

2015年(1)

2014年(3)

2013年(13)

2012年(18)

2011年(150)

分类: Java

2012-09-20 09:14:59

  假如创建线程的时间开销为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(t != 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()方法即可
阅读(10047) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~