您当前的位置: 首页 >  Java

Dongguo丶

暂无认证

  • 0浏览

    0关注

    472博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java线程池

Dongguo丶 发布时间:2017-12-09 20:51:52 ,浏览量:0

为什么要使用线程池
  • 降低资源消耗: 通过重复利用线程,减少线程的创建销毁损耗的资源
  • 提高响应速度: 任务到达时,不用重新创建线程,之间可以使用已经创建好的线程执行
  • 提高线程的可管理性
线程池实现分析

我们使用如下的demo来一步一步分析线程池


public class TheadPoolTest {

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

                ExecutorService service = Executors.newFixedThreadPool(2);
                // ExecutorService service = Executors.newCachedThreadPool();
                // ExecutorService service = Executors.newWorkStealingPool();

                for (int i = 0; i < 4; i++) {
                    service.submit(getTask());
                    //如果都是不需要返回结果的Runnable可以直接使用
                     //service.execute(getTask());
                }
            }

            private static Runnable getTask() {
                return new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getId());
                    }
                };
            }
        }

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
1.初始化构造线程池

Executors是一个工厂类,里面封装了多个用于创造特定场景下使用的线程池的工厂方法。比如我们示例中的Executors.newFixedThreadPool(2)会返回一个固定线程个数的线程池。详细来看看


//Executors:
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue());
    }


//ThreadPoolExecutor:
    private static final RejectedExecutionHandler defaultHandler =
        new AbortPolicy();

    private static final RuntimePermission shutdownPerm =
        new RuntimePermission("modifyThread");


    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize             
关注
打赏
1638062488
查看更多评论
0.0428s