java线程池

来源:互联网 发布:virtualbox 安装mac 编辑:程序博客网 时间:2024/05/18 20:31
package com.ly.thread;import java.util.LinkedList;/**线程池 * @author 牵手无奈 * date:2015-10-14 * */public class ThreadPool extends ThreadGroup{private int poolSize;private static int threadPoolID;private boolean isClosed;private LinkedList<Runnable> workQueue;//工作任务队列private int ThreadID;public ThreadPool(int size){super("ThreadPool id="+threadPoolID++);this.poolSize=size;setDaemon(true);workQueue = new LinkedList<>();for(int i=0;i<poolSize;i++){new WorkThread().start();//先运行多个线程,随时准备通过它来执行任务}}/**执行提交的任务 * @param task */public synchronized void execute(Runnable task){if(isClosed){throw new IllegalThreadStateException();}else{workQueue.add(task);notify();//唤醒在等待获取任务执行的线程}}public synchronized Runnable getTask() throws InterruptedException{while(workQueue.size()==0){if(isClosed) return null;wait();System.out.println("唤醒了一个线程");}return workQueue.removeFirst();}public synchronized void close(){if(!isClosed){isClosed=true;workQueue.clear();}interrupt();}public void join(){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 (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private class WorkThread extends Thread{public WorkThread(){super(ThreadPool.this,"WorkThread"+ThreadID++);}@Overridepublic void run() {while (!isInterrupted()) {Runnable task = null;try {task=getTask();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(task==null){return;}else{task.run();}}}}public static void main(String[] args){ThreadPool tp = new ThreadPool(3);try {Thread.sleep(2000);} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}for( int i=0;i<10;i++){tp.execute(new Runnable() {@Overridepublic void run() {System.out.println("1");try {Thread.sleep(5000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}tp.join();}}

0 0
原创粉丝点击