package com.anda.threads; import java.util.LinkedList; /** * 自定义线程池 * * @author Admin * */ public class ThreadPool extends ThreadGroup { private static boolean isClose = false;// 线程池是否关闭 private static LinkedList workQueue; // 工作队列 private static ThreadPool pool = null; private static Integer num = 0; public static ThreadPool getInstance() { if (pool == null) { pool = new ThreadPool(20); } return pool; } /** * 初始化线程池 * * @param poolSize */ private ThreadPool(int poolSize) { super("zaichi thread pool"); setDaemon(true); workQueue = new LinkedList(); for (int i = 0; i < poolSize; i++) { new WorkThread(i).start(); } } public synchronized void execute(Runnable task) { if (isClose) { throw new IllegalStateException(); } if (task != null) { num++; workQueue.add(task); notify(); } } // 从工作队列中取出一个任务,工作线程会调用该方法 private synchronized Runnable getTask(int threadId) throws InterruptedException { while (workQueue.size() == 0) { if (isClose) { return null; } wait(); // 如果工作线程中没有任务,那么就等待着 } return (Runnable) workQueue.removeFirst(); // 返回队列中的第一个元素,并从队列中删除 } // 等待工作线程把任务执行完成 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 closePool() { if (!isClose) { waitFinish(); // 等待工作线程执行完毕 isClose = true; workQueue.clear(); // 清空工作队列 interrupt(); // 中断线程池所有的工作线程 } } /** * 多线程的工作线程 * * @author Admin * */ private class WorkThread extends Thread { private int id; public WorkThread(int id) { super(ThreadPool.this, id + ""); this.id = id; } public void run() { while (!isInterrupted()) { // 继承自Thread,判断线程是否被中断 Runnable task = null; try { task = getTask(id); // 取出任务 } catch (InterruptedException e) { e.printStackTrace(); } // 如果getTask()返回null或者线程执行getTask()时被中断,则结束此线程 if (task == null) { return; } task.run(); // 运行任务 } } } }
自定义Java多线程池
猜你喜欢
转载自sharejava.iteye.com/blog/2229265
今日推荐
周排行