自己写的线程池的小例子


    /**
     * 任务队列,将,要执行的所有任务放到队列里,等线程池里边的线程有空闲时再继续执行任务。
     * @author Administrator
     */
    private final static Logger LOG = LogManager.getLogger(ThreadPool.class);
    private final PoolTask[] threads;
    private final BlockingQueue<Object> queue;
    private final Random rand = new Random();
    public ThreadPool(int nThreads){
        queue = new LinkedBlockingQueue<Object>();
        threads = new PoolTask[nThreads];
        for (int i=0; i<nThreads; i++){
            threads[i] = new PoolTask();
            threads[i].start();
        }

    }

 

    public void execute(Runnable r) {
        int i = rand.nextInt(threads.length);
        threads[i].execute(r);

    }

 

    public void quitQueue() {       
        for (int i = 0; i < threads.length; i++) {
            threads[i].execute(new EmptyTask());
        }       
        for (int i = 0; i < threads.length; i++) {           
            try {               
                threads[i].join();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
   
    private class PoolTask extends Thread {
        public void execute(Runnable r) {
            try {
                queue.put(r);
            } catch (InterruptedException e) {
                LOG.debug("任务添加失败!", e);
            }
        }
        public void run() {
            Runnable r = null;
            while (true) {
                try {
                    r = (Runnable)queue.take();
                } catch (InterruptedException e) {
                    LOG.debug("获取任务失败!", e);
                }
                try {
                    r.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(r instanceof EmptyTask) {
                        break;
                    }
                }
            }
        }
    }
    public class EmptyTask implements Runnable {
        public void run() {}

    }

}

 

调用的时候:

        ThreadPool threadPool = new ThreadPool(THREAD_COUNT);

        //处理业务逻辑线程
        ConnectMember conMember=new ConnectMember();
        conMember.setInit(sessionId, req, out);
        threadPool.execute(conMember);
        threadPool.quitQueue();//取消队列任务

 

 

 

转载于:https://my.oschina.net/aicoding/blog/65054

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值