Java单线程池

package com.hebei.read.core.plugins.thread;

import java.util.LinkedList;

/**
 * 自定义线程池
 * 
 * @author Admin
 * 
 */
public class SinglePool extends ThreadGroup {

	private static boolean isClose = false;// 线程池是否关闭
	private static LinkedList workQueue; // 工作队列
	private static SinglePool pool = null;
	private static WorkThread work = null;

	public static SinglePool getInstance() {
		if (pool == null) {
			pool = new SinglePool();
		}
		return pool;
	}

	/**
	 * 初始化线程池
	 * 
	 * @param poolSize
	 */
	private SinglePool() {
		super("zaichi thread group");
		setDaemon(true);
		workQueue = new LinkedList();
		work = new WorkThread();
		work.start();
	}

	public synchronized void execute(Runnable task) {
		if (isClose) {
			throw new IllegalStateException();
		}
		if (task != null) {
			workQueue.add(task);
			notify();
		}
	}

	// 从工作队列中取出一个任务,工作线程会调用该方法
	private synchronized Runnable getTask() throws InterruptedException {
		while (workQueue.size() == 0) {
			if (isClose) {
				return null;
			}
			wait(); // 如果工作线程中没有任务,那么就等待着
		}
		return (Runnable) workQueue.removeFirst();// 返回队列中的第一个元素,并从队列中删除
	}

	/**
	 * 线程是否在运行
	 * 
	 * @return
	 */
	public synchronized boolean isRunning(Thread t) {
		return workQueue.size() > 0 || work.isRunning();
	}

	/**
	 * 线程是否在运行
	 * 
	 * @return
	 */
	public synchronized boolean isRunning() {
		return workQueue.size() > 0 || work.isRunning();
	}

	// 等待工作线程把任务执行完成
	private void waitFinish() {
		synchronized (this) {
			isClose = true;
			notifyAll(); // 唤醒所有还在getTask()方法中等待任务的工作线程
		}
		Thread[] threads = new Thread[activeCount()]; // activeCount()返回该线程组中活动线程的估计值
		int count = enumerate(threads); // enumerate方法继承自ThreadGroup,根据活动的线程的估计值获得该线程组中当前所有活动的工作线程
		for (int i = 0; i < count; i++) { // 等待所有工作线程结束
			try {
				threads[i].join(); // 等待工作线程结束
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	// 关闭线程池
	public synchronized void shutdown() {
		if (!isClose) {
			waitFinish(); // 等待工作线程执行完毕
			isClose = true;
			workQueue.clear(); // 清空工作队列
			interrupt(); // 中断线程池所有的工作线程
		}
	}

	/**
	 * 多线程的工作线程
	 * 
	 * @author Admin
	 * 
	 */
	private class WorkThread extends Thread {

		private boolean running = false;
		private int m = 0;

		public WorkThread() {
			super(SinglePool.this, "zaichi single thread");
		}

		public boolean isRunning(int n) {
			if (m == n) {
				return running;
			} else {
				return false;
			}
		}

		public boolean isRunning() {
			return running;
		}

		public void run() {
			while (!isInterrupted()) { // 继承自Thread,判断线程是否被中断
				Runnable task = null;
				try {
					task = getTask(); // 取出任务
					m = task.hashCode();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 如果getTask()返回null或者线程执行getTask()时被中断,则结束此线程
				if (task == null) {
					return;
				}
				running = true;
				task.run(); // 运行任务
				running = false;
			}
		}
	}
}

猜你喜欢

转载自sharejava.iteye.com/blog/2229266
今日推荐