newCachedThreadPool使用案例

Posted jinjian91

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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());
                }
            });

        }


    }
}

线程被重用

适合场景:流量洪峰一波一波的来,

 

以上是关于newCachedThreadPool使用案例的主要内容,如果未能解决你的问题,请参考以下文章

可缓存线程池newCachedThreadPool

多线程——newCachedThreadPool线程池

线程池Executors.newCachedThreadPool

Java 并发编程线程池机制 ( 线程池示例 | newCachedThreadPool | newFixedThreadPool | newSingleThreadExecutor )

java线程池之newCachedThreadPool

java 线程池 ---- newCachedThreadPool()