自己写的线程池

1 .线程池类:TPTaskProxy

 

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TPTaskProxy {
	
	private static Log log = LogFactory.getLog(TPTaskProxy.class);
		/**
		 * 添加任务并唤醒各因无任务而等待的空闲线程
		 * 
		 * @param task
		 * @throws JobException
		 */
		public void executeTask(TPTask task) {
			synchronized (taskQueue) {
				try {
					taskQueue.add(task);
					taskQueue.notifyAll();
				} catch (Exception e) {
	
				}
			}
		}
		
		public static int DEFAULT_POOL_SIZE = 10;
		
		/**
		 * 任务队列
		 */
		private Queue<TPTask> taskQueue;
		
		/**
		 * 空闲线程
		 */
		private Queue<TPTaskThread> idleThread;
		
		/**
		 * 线程池大小
		 */
		private int taskPoolSize ;
		
		public int getQueueSize(){
			return taskQueue.size();
		}
		
		public TPTaskProxy() {
			if (taskPoolSize < 0) {
				this.taskPoolSize = DEFAULT_POOL_SIZE;
			}
			taskQueue = new ConcurrentLinkedQueue<TPTask>();
			idleThread = new ConcurrentLinkedQueue<TPTaskThread>();
		}
	
		
		/**
		 * 初始化线程池,新建 N 个空闲线程
		 * 
		 */
		public void init() {
			log.debug("init");
			log.debug("taskPoolSize="+taskPoolSize);
			for (int i = 0; i < taskPoolSize; i++) {
				TPTaskThread taskThread = new TPTaskThread(this, taskQueue,"Thread " + i);
				idleThread.add(taskThread);
					taskThread.start();
			}
		}
		
		/**
		 * 关闭线程池,关闭线程池中各个线程 在调用该方法后,线程并没有马上关闭,而是在线程任务执行完之后关闭
		 * 
		 */
		public void shutDown() {
			synchronized (taskQueue) {
				for (TPTaskThread thread : idleThread) {
					thread.shutDown();
				}
			}
		}
		
		public void startAll() {
			synchronized (taskQueue) {
				for (TPTaskThread thread : idleThread) {
					thread.setBegin(true);
				}
				taskQueue.notifyAll();
			}
		}
		
		public void stopAll() {
			synchronized (taskQueue) {
				for (TPTaskThread thread : idleThread) {
					thread.setBegin(false);
				}
			}
		}
		

		/**
		 * 获取空闲线程,当线程池内无空闲线程时等待
		 * 
		 * @return
		 * @throws JobException
		 */
		public TPTaskThread getIdleThread(){
			if (idleThread.isEmpty()) {
				try {
					idleThread.wait();
				} catch (InterruptedException e) {
					 
				}
			}
			synchronized (idleThread) {
				return idleThread.poll();
			}
		}

		/**
		 * 释放线程
		 * 
		 * @param thread
		 */
		public void releaseThread(TPTaskThread thread) {
			synchronized (idleThread) {
				idleThread.add(thread);
				idleThread.notifyAll();
			}
		}

		public void setTaskPoolSize(int taskPoolSize) {
			this.taskPoolSize = taskPoolSize;
		}
}

 

 

2 .线程实现类:TPTaskThread

import java.util.Queue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TPTaskThread extends Thread{
	
	private static  Log log = LogFactory.getLog(TPTaskThread.class);
	/**  
     * 线程关闭的标识位  
     */  
    private boolean shutDown = false; 
    private boolean begin = true;
    /**  
     * 任务队列  
     */  
    private Queue<TPTask> taskQueue; 
    
    private TPTaskProxy persistentProxy;
    
	public TPTaskThread(TPTaskProxy persistentProxy,
			Queue<TPTask> taskQueue, String name) {
		super(name);   
		log.debug("make "+this);
		System.out.println("make :::"+this);
		this.taskQueue = taskQueue;
		this.persistentProxy = persistentProxy;
	}

	public void shutDown() {
		this.shutDown = true;   
	}
	
	public void setBegin(boolean begin){
		this.begin = begin;
	}
	
    public void run() {   
        while(!shutDown) {   
            TPTask task;   
            // 如果任务队列不为空,则取出一个任务并开始执行,否则线程等等   
            if(!taskQueue.isEmpty() && begin) {
                synchronized(taskQueue) {   
                    task = taskQueue.poll();  
                } 
                //多线程抢task,如果没有抢到,直接release.
                if(task!=null)
                task.doTask();
                // 任务执行完毕之后释放线程到空闲线程队列中   
                persistentProxy.releaseThread(this);   
            } else {   
                try {   
                    synchronized(taskQueue) {
                        taskQueue.wait();   
                    }   
                } catch (InterruptedException e) {
                    
                }   
            }   
        }   
    }   

}

 

3 .要执行的任务类:TPTask

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TPTask {
	
	private Object target;
	private String methodName;
	private Object[] params;
	private Class<?>[] types;
	
	public TPTask(Object target,String methodName,Object[] params,Class<?>[] types){
		this.target = target;
		this.methodName = methodName;
		this.params = params;
		this.types = types;
	}
	
	public void doTask(){
		try {
			Method method = null;
			if(params.length > 0)
				method = target.getClass().getMethod(methodName, types);
			else 
				method = target.getClass().getMethod(methodName);
			
			method.invoke(target, params);
		} 
		catch (SecurityException e) {
			e.printStackTrace();
		} 
		catch (NoSuchMethodException e) {
			e.printStackTrace();
		} 
		catch (IllegalArgumentException e) {
			e.printStackTrace();
		} 
		catch (IllegalAccessException e) {
			e.printStackTrace();
		} 
		catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}

 

使用:

TPTaskProxy proxy = new TPTaskProxy();
//设置线程池的大小
int poolSize = 100;
proxy.setTaskPoolSize(poolSize);
proxy.init();
//目标对象,可以是任何类型对象
TargetObject target = new TargetObject();
proxy.executeTask(new TPTask(target,"methodName",
	new Object[]{agr1,	arg2,}
	,new Class<?>[]{arg1.class,arg2.class}));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值