缓存线程池的作用

JAVA提供4种缓存线程池

  • newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
  • newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
  • newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
  • newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

 

 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 缓存线程池
 * 缓存线程池可以提高程序性能
 * 长时间闲置的不会占用资源
 * */

public class MyCache {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int index = 0; index < 10; index++) {
            Runnable run = new Runnable() {
                public void run() {
                    long time = (long) (Math.random() * 1000);
                    System.out.println("sleep:" + time + " ss ");
                    try {
                        Thread.sleep(time);
                    } catch (Exception e) {
                    }
                }
            };
            exec.execute(run);
        }
        exec.shutdown();
    }

}

 

转载于:https://www.cnblogs.com/zique/p/6152845.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值