线程池7个参数拿捏死死的,完爆面试官

2022-06-21  本文已影响0人  Java架构领域
image.png

线程池

image.png image.png image.png image.png image.png image.png image.png

核心数与总线程数

 final ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
         executorService.execute(new Runnable() {
             @Override
             public void run() {
                 System.out.println("我是线程1做的事情");
             }
         });
复制代码
 public static ExecutorService newFixedThreadPool(int nThreads) {
         return new ThreadPoolExecutor(nThreads, nThreads,
                                       0L, TimeUnit.MILLISECONDS,
                                       new LinkedBlockingQueue<Runnable>());
     }
复制代码
image.png image.png image.png image.png
 int c = ctl.get();
         if (workerCountOf(c) < corePoolSize) {
             if (addWorker(command, true))
                 return;
             c = ctl.get();
         }
         if (isRunning(c) && workQueue.offer(command)) {
             int recheck = ctl.get();
             if (! isRunning(recheck) && remove(command))
                 reject(command);
             else if (workerCountOf(recheck) == 0)
                 addWorker(null, false);
         }
         else if (!addWorker(command, false))
             reject(command);
     }
复制代码

思考

 public static void main(String[] args) throws InterruptedException {
         ThreadPoolExecutor executorService = new ThreadPoolExecutor(10,20,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
         for (int i = 0; i < 100; i++) {
             int finalI = i;
             executorService.execute(new Runnable() {
                 @SneakyThrows
                 @Override
                 public void run() {
                     System.out.println(finalI);
                     TimeUnit.SECONDS.sleep(1000);
                 }
             });
         }
     }
复制代码
image.png
原链: https://juejin.cn/post/7111131220548780062
上一篇 下一篇

猜你喜欢

热点阅读