zoukankan      html  css  js  c++  java
  • newCachedThreadPool使用案例

    newCachedThreadPool 缓存默认60s

    猜下你的结果

    package com.juc.threadpool;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * Created by Administrator on 2018/6/27.
     */
    public class CachedThreadPoolDemo {
    
    
        public static void main(String[] args) throws InterruptedException {
    
            ExecutorService executorService = Executors.newCachedThreadPool();
            for (int i = 0; i < 10; i++) {
                final int s = i;
                executorService.execute(() -> {
                    try {
                        System.out.println("" + s + ";;;" + Thread.currentThread().getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            Thread.sleep(2000);//2s
            executorService.execute(() -> {
                try {
    
                    System.out.println(";;;" + Thread.currentThread().getName());
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
    
        }
    }

    线程被复用一次

    package com.juc.threadpool;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * Created by Administrator on 2018/6/27.
     */
    public class CachedThreadPoolDemo {
    
    
        public static void main(String[] args) throws InterruptedException {
    
            ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
            for (int i = 0; i < 10; i++) {
                final int index = i;
                try {
                    System.out.println("睡起来...");
                    Thread.sleep(index * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cachedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(index + "当前线程" + Thread.currentThread().getName());
                    }
                });
    
            }
    
    
        }
    }

    线程被重用

    缓存线程池无核心线程,队列只能存一个任务,导致它会无限创建线程

    适合场景:流量洪峰一波一波的来,在线程没回收之前进行重复利用最好

  • 相关阅读:
    idea如何使用git关联远程仓库
    项目首次上传至git仓库步骤
    Eclipse 的 Java Web 项目环境搭建
    Postman
    Postman接口测试之POST、GET请求方法
    接口测试3A原则
    使用unittest和ddt进行数据驱动
    每天进步一点点006
    每天进步一点点005
    Selenium2+python自动化1-环境搭建(悠悠课程之路)
  • 原文地址:https://www.cnblogs.com/jinjian91/p/9236648.html
Copyright © 2011-2022 走看看