实现线程池

1.线程池优点:
1).减少创建和销毁线程的次数
2).可以根据系统的能力,调整线程池中线程的数目
3).减少切换线程的开销

2.实现自定义线程池
思路:
1)将线程池线程定义为守护线程(这样可以保证在线程池中的线程结束后自动退出,同时监视线程池)
2)创建一个工作队列保存线程(Runnable)
3)执行线程的类
4)定义线程池的状态参数
实现:

public class ThreadPool extends ThreadGroup {

    private boolean isClosed = false; //线程池是否关闭
    private LinkedList<Runnable> workQueue; //工作队列
    private static int threadPoolID; //线程池ID
    private int threadID; //工作线程的ID

    public ThreadPool(int poolSize){

        super("ThreadPool-" + (threadPoolID++));  //ThreadGroup(String name),线程池名字
        setDaemon(true); //设置为守护线程
        workQueue = new LinkedList<Runnable>();
        for(int i=0; i<poolSize; i++){
            new WorkThread().start(); //启动线程
        }
    }

    //加入任务
    public synchronized void execute(Runnable task){

        if(isClosed){
            throw new IllegalStateException();
        }
        if(task !=null){
            workQueue.add(task);
            notify();
        }
    }
    //获取线程任务
    public synchronized Runnable getTask()throws Exception{
        while(workQueue.size() == 0){
            if(isClosed){
                return null;
            }
            wait();
        }
        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) {
                e.printStackTrace();
            }
        }
    }
    //工作线程类
    private class WorkThread extends Thread{

        public WorkThread(){
            //加入线程组
            super(ThreadPool.this,"WorkThread" + (threadID++));
        }

        public void run(){

            while(!isInterrupted()){  //isInterrupted(),继承于Thread类,判断线程是否被中断

                Runnable task = null;
                try {
                    task = getTask();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(task == null){
                    return;
                }

                task.run();
            }
        }
    }

}

过程:在指定个数的线程中执行加入的任务,当队列为空但线程池未关闭时,在此等待,等待其他线程在有任务时唤醒或者线程中断关闭

测试类:

public class ThreadPoolTest {

    public static void main(String[] args) {

        if (args.length != 2) {
            System.out.println("please input args");
            return;
        }

        int numTasks = Integer.parseInt(args[0]);
        int poolSize = Integer.parseInt(args[1]);

        //创建线程池
        ThreadPool threadPool = new ThreadPool(poolSize);

        for (int i = 0; i < numTasks; i++) {

            threadPool.execute(createTask(i));
        }
        threadPool.join();

    }
    //执行的任务
    private static Runnable createTask(final int taskID) {

        return new Runnable() {
            public void run() {

                System.out.println("Task" + taskID + "start");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task" + taskID + "end");

            }
        };
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值