自己动手写线程池

线程池 = 有界/无界队列<Runable> + List<Thread> + 饱和策略

自己动手写线程池-LMLPHP

import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {


    private BlockingQueue<Runnable> blockingQueue = null;

    private ArrayList<Thread> allThreads = null;

    private boolean isWorking = true;

    MyThreadPool(int poolSize,int queueSize){
        blockingQueue = new LinkedBlockingQueue(queueSize);
        allThreads = new ArrayList<>(poolSize);
        for(int i = 0 ; i < poolSize; i++){


            Worker thread = new Worker(this);

            allThreads.add(thread);

            thread.start();
        }
    }


    private static class Worker extends Thread{
        MyThreadPool pool;
        Worker(MyThreadPool pool){
            this.pool = pool;
        }

        @Override
        public void run() {
            while (pool.isWorking || pool.blockingQueue.size() > 0) {
                try {
                    Runnable runnable = pool.blockingQueue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                 //   e.printStackTrace();
                }
            }
        }
    }

    public boolean subumit(Runnable runnable) throws InterruptedException {
       return  blockingQueue.offer(runnable);
    }

    /**两个问题:
     * 1.阻塞在take地方的怎么把他停掉?InterruptedException
     * 2.保证已经在queue里面的Runable要执行完成.  pool.blockingQueue.size() > 0
     */
    public void shutDown(){
        isWorking = false;
        for(Thread thread : allThreads){
            thread.interrupt();
        }
    }


    public static void main(String[] argv) throws InterruptedException {

        int threadCount = 100;

        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        MyThreadPool myThreadPool = new MyThreadPool(5,10);

        for(int i=0 ; i < threadCount; i++){
            boolean isAccept = myThreadPool.subumit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                     //   e.printStackTrace();
                    }
                    System.out.println("thread " + Thread.currentThread().getName() + " run");
                  //  countDownLatch.countDown();
                }
            });
            if(isAccept){
                System.out.println("Thread " + i + "has been Submit");
            }
        }

      //  countDownLatch.await();

        Thread.sleep(100);

        myThreadPool.shutDown();
    }


}

线程池被请求打满的原因有两个,一个是核心线程数太少,还有可能是线程runnable的任务耗时变长导致处理不过来。

解决方法一个是增大核心线程数;二是检查是否run里面有可以优化的耗时操作.

05-31 19:12