java-threadpool

本文介绍了一个简单的Java线程池实现方法,通过继承ThreadGroup并使用LinkedList作为任务队列。该线程池采用单例模式,并支持添加任务及关闭线程池等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Filename: ThreadPool.java
 * 
 * @Copyright: Copyright (c)2013 Company:  
 * 
 * @author:  
 * @version: 1.0 Create at: 2013-11-4 上午09:25:08
 */
public class ThreadPool extends ThreadGroup {
	private boolean isClosed = false;
	private static ThreadPool threadPool;
	private static LinkedList<Runnable> workQueue;
	// 启动线程池中的线程
	private ThreadPool(Integer poolSize) {
		super(new Date().getTime() + ":" + threadPool);
		workQueue = new LinkedList<Runnable>();
		for (int i = 0; i < poolSize; i++) {
			new WorkThread(i).start();
		}
		try {
			Thread.sleep(2000); // 线程池准备线程
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //
	}

	// 初始化单列模式线程池
	public static ThreadPool getInstance() {
		if (threadPool == null)
			threadPool = new ThreadPool(50);
		return threadPool;
	}

	public synchronized void execute(Runnable task) {
		if (task != null ) {
			try {
				workQueue.add(task);
				System.out.println("execute task.....");
				notify();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private synchronized Runnable getTask(int threadid) throws InterruptedException {
		while (workQueue.size() == 0) {
			if (isClosed)
				return null;
			System.out.println("work thread--------" + threadid + " wait");
			wait(threadid);
		}
		System.out.println("work thread--------" + threadid + " run");
		return workQueue.removeFirst();
	}

	/*
	 * 关闭线程池
	 */
	public synchronized void closePool() {
		if (!isClosed) {
			waitFinish(); // 等待工作线程执行完毕
			isClosed = true;
			System.out.println("thread is over........");
			workQueue.clear(); // 清空工作队列
			interrupt(); // 中断线程池中的所有的工作线程,此方法继承自ThreadGroup类
		}
	}

	/**
	 * 等待所有线程运行完毕
	 */
	public void waitFinish() {
		synchronized (this) {
			isClosed = true;
			notifyAll();
		}
		Thread[] threads = new Thread[activeCount()]; // 已激活处于等待中的线程
		int count = enumerate(threads);
		for (int i = 0; i < count; i++) {
			try {
				threads[i].join(); // 等待所有线程执行完毕
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private class WorkThread extends Thread {
		private int id;

		private WorkThread(int id) {
			super(ThreadPool.this, id + "");
			this.id = id;
		}

		public void run() {
			while (!isInterrupted()) {
				Runnable task = null;
				try {
					task = getTask(id);
					if (task == null)
						return;
					task.run();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值