多线程中线程池的简单实现

来源:互联网 发布:康德…知乎 编辑:程序博客网 时间:2024/05/16 08:37
import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;/** * @ClassName: ThreadPool * @Description: TODO(线程池) * @author GODDESS * @date Apr 3, 2017 4:55:11 PM *  */public class ThreadPool {    // 空闲的线程队列    private List<PThread> idleThreads;    private int threadCounter;    private volatile boolean isShutDown = false;    private ThreadPool() {        this.idleThreads = new CopyOnWriteArrayList<PThread>();        this.threadCounter = 0;    }    private static class ThreadHolder {        private static ThreadPool pool = new ThreadPool();    }    public static ThreadPool getInstance() {        return ThreadHolder.pool;    }    public int getCreatedThreadCounter() {        return threadCounter;    }    public void repool(PThread pThread) {        if (!isShutDown) {            idleThreads.add(pThread);        } else {            pThread.shutDown();        }    }    // 停止线程池中所有的线程    public synchronized void shutDown() {        isShutDown = true;        PThread thread = null;        for (int i = 0; i < idleThreads.size(); i++) {            thread = idleThreads.get(i);            thread.shutDown();        }    }    public synchronized void start(Runnable target) {        PThread thread = null;        if (idleThreads.size() > 0) {            int lastIndex = idleThreads.size()-1;            thread = idleThreads.get(lastIndex);            idleThreads.remove(lastIndex);            thread.setTarget(thread);        }        //如果没有线程空闲        else{            threadCounter++;            //创建线程            thread = new PThread(this, target, "PThread #"+threadCounter);            //启动这个线程            thread.start();        }    }}

要使用上述的线程池,需要一个永不退出的线程与它配合。PThread就是这样一个线程,他的线程主体是个无线循环,该线程在手动关闭之前永不会结束,并一直等待分配新的任务。

/**  * @ClassName: PThread  * @Description: TODO(这里用一句话描述这个类的作用)  * @author GODDESS * @date Apr 3, 2017 4:58:04 PM  *  */public class PThread extends Thread{    private ThreadPool threadPool;    private Runnable target ;    private boolean isShutDown = false;    private boolean isIdle = false;//是否空闲    public PThread(ThreadPool threadPool, Runnable target,String name) {        super(name);        this.threadPool = threadPool;        this.target = target;    }    public Runnable getTarget() {        return target;    }    public boolean isIdle() {        return isIdle;    }    @Override    public void run() {        //只要没有关闭,则一直不结束现成        try {            while(!isShutDown){                isIdle = false;                if(target!=null){                    target.run();                }                //任务结束了,到空闲状态                isIdle = true;                //任务结束后不关闭现成,而是放入线程池空闲队列                threadPool.repool(this);                synchronized(this){                    //线程空闲,等待新的任务到来                    wait();                }                isIdle = false;            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }    public synchronized void setTarget(Runnable target) {        this.target = target;        //设置了任务后,通知run方法,开始执行这个任务        notifyAll();    }    public synchronized void shutDown(){        isShutDown = true;        notifyAll();    }}

使用线程池后,线程的穿件和关闭通常由线程池维护。线程通常不会因为执行完一次任务而关闭,线程池中的线程会被多个任务重复使用。

下面看我们如何使用上面的线程池:

public class ThreadTest {    public static void main(String[] args) {        for(int i = 0;i<10;i++){            ThreadPool.getInstance().start(new MyThread("Thread#"+i));        }        System.out.println(ThreadPool.getInstance().getCreatedThreadCounter());    }    private static class MyThread implements Runnable{        protected String name;        public MyThread(String name) {            this.name = name;        }        @Override        public void run() {            try {                Thread.sleep(1000);                System.out.println(name+"这个厉害了");            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

输出结果:

10Thread#9这个厉害了Thread#5这个厉害了Thread#3这个厉害了Thread#2这个厉害了Thread#1这个厉害了Thread#7这个厉害了Thread#4这个厉害了Thread#0这个厉害了Thread#6这个厉害了Thread#8这个厉害了
0 0
原创粉丝点击