自己写的线程池

线程池实践

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}));

 

自己实现一个简单的线程池,可以通过以下步骤完成: 1. 定义一个任务接口`Task`,用来表示需要执行的任务。 ``` public interface Task { void execute(); } ``` 2. 定义一个工作线程类`WorkerThread`,用来执行任务。 ``` public class WorkerThread extends Thread { private final BlockingQueue<Task> taskQueue; public WorkerThread(BlockingQueue<Task> taskQueue) { this.taskQueue = taskQueue; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { Task task = taskQueue.take(); task.execute(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } ``` 3. 定义一个线程池类`ThreadPool`,用来管理线程池。 ``` public class ThreadPool { private final int nThreads; private final BlockingQueue<Task> taskQueue; private final List<WorkerThread> threads = new ArrayList<>(); public ThreadPool(int nThreads, int queueSize) { this.nThreads = nThreads; taskQueue = new LinkedBlockingQueue<>(queueSize); for (int i = 0; i < nThreads; i++) { WorkerThread workerThread = new WorkerThread(taskQueue); threads.add(workerThread); workerThread.start(); } } public void execute(Task task) throws InterruptedException { taskQueue.put(task); } public void shutdown() { for (WorkerThread thread : threads) { thread.interrupt(); } } } ``` 在上面的代码中,我们使用`BlockingQueue`来存储任务队列,用`WorkerThread`来执行任务,使用`ThreadPool`来管理线程池。 4. 使用线程池来执行任务。 ``` public class Main { public static void main(String[] args) throws InterruptedException { ThreadPool threadPool = new ThreadPool(5, 10); for (int i = 0; i < 20; i++) { int taskId = i; threadPool.execute(new Task() { @Override public void execute() { System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } threadPool.shutdown(); } } ``` 在上面的代码中,我们使用自己实现的线程池来执行20个任务,每个任务需要执行1秒钟,最后关闭线程池。 注意,这个自己实现的线程池只是一个简单的示例,没有考虑线程池的扩展性、性能等问题。在实际应用中,建议使用Java提供的线程池实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值