Java线程池的设计与分析

1.线程池的好处

合理利用线程池可以带来三个好处:缓存

  • 下降资源消耗并发

  • 提升响应速度ide

  • 提升线程的可管理性spa

2.线程池的使用

咱们能够经过ThreadPoolExecutor来建立一个线程池:线程

new  ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, milliseconds,runnableTaskQueue, handler);

建立一个线程池须要输入几个参数:code

  • corePoolSize - 线程池的基本大小队列

  • maximumPoolSize -线程池最大大小资源

  • keepAliveTime - 线程活动保持时间get

  • runableTaskQueue - 任务队列it

 

3.线程池工做原理

 

经过线程池的处理流程以下:

1.首先线程池判断基本线程池是否已满?没满,建立一个工做线程来执行任务。满了,则进入下个流程

2.其次线程池判断工做队列是否已满?没满,则将新提交的任务存储在工做队列里。满了,则进入下个流程

3.最后线程池判断整个线程池是否已满? 没满, 则建立一个新的工做线程来执行任务, 满了则交给饱和策略来处理任务

 

4.线程池的四种实现

Java经过Executors提供了四种线程池:

  • newCachedThreadPool 建立一个可缓存的线程池, 若是线程池长度超过处理须要,可灵活回收空闲线程,若无可回收,则新建线程

      newCacheThreadPool源代码分析以下:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

 

   实现的是SynchronousQueue

  • newFixThreadPool: 建立一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

    newFixThreadPool源代码:

  • public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

 

  • newScheduledTheadPool:建立一个定长线程池, 支持定时及周期任务执行

    newScheduledThreadPool源代码分析:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
  • newSingleThreadPool:建立一个单线程化的线程池

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

 

项目中使用

public class ThreadPoolTest {

    static class ExecutePrint implements Task {

        @Override
        public String getName() {
            return "threadpool";
        }

        @Override
        public void shutdown() {

        }

        @Override
        public void run() {
            System.out.println("hello world");

        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(5000), new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolExecutor.submit(new ExecutePrint());
    }
}
public class ThreadPoolTest2 {

    public static void main(String[] args) {
       // ExecutorService executorService = Executors.newCachedThreadPool();
        //ExecutorService executorService = Executors.newFixedThreadPool(10);
        //ExecutorService executorService = Executors.newScheduledThreadPool(10);
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for(int i =0; i <10;i++){
            final int index = i;
            try {
                Thread.sleep(index*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(index);
                }
            });
        }
    }
}
相关文章
相关标签/搜索