• java 线程池 Executors,ExecutorService


    1,线程池对象

    1,Executors 工厂类

    • 方法 newFixedThreadPool(int num),创建固定个数线程池,num 代表线程个数

    • 方法 newCachedThreadPool(),创建弹性个数的线程池,当忙碌时,会不断创建线程,当空闲时,会回收线程

    2,ExecutorService 线程池

    3,线程计数器 CountDownLatch

    • new CountDownLatch(10),一般实例化会传入具体等待几个线程
    • countDownLatch.countDown(),会把传入的值 减一,当数字是 0 的时候会继续往下执行
    • countDownLatch.await(60, TimeUnit.HOURS) ,等待countDownLatch.countDown()将传入的值减到0,当超时的时候也会继续往下执行

    2,简单的使用

    package com.hwq.admin.back.service;
    
    import com.hwq.common.exception.ServerException;
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    
    @Service
    public class ThreadPoolService {
    
        private final ExecutorService executorService = Executors.newFixedThreadPool(5);
    
        public List<String> listPoolName() {
            CountDownLatch countDownLatch = new CountDownLatch(10);
            List<String> list = new ArrayList<>();
            List<String> synList = Collections.synchronizedList(list);  // 注意线程安全
            for (int i = 0; i < 10; i++) {
                executorService.execute(() -> {
                    try {
                        Thread.sleep(1000);
                        Thread t = Thread.currentThread();
                        synList.add(t.getId() + " : " + t.getName());
                        countDownLatch.countDown();           // 通知计数器完成任务
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
    
            try {
                countDownLatch.await(60, TimeUnit.SECONDS);   // 线程等待
                return list;
            } catch (InterruptedException ex) {
                throw new ServerException(ex);
            }
        }
    }
    
  • 相关阅读:
    13.Odoo产品分析 (二) – 商业板块(6) –采购(3)
    9.Odoo产品分析 (二) – 商业板块(4) –讨论(1)
    10.Odoo产品分析 (二) – 商业板块(5) –日历(1)
    8.Odoo产品分析 (二) – 商业板块(3) –CRM(2)
    7.Odoo产品分析 (二) – 商业板块(3) –CRM(1)
    the nearest point/vertex point of linestring
    Clojure的引用类型:var,ref,agent和atom
    clojure的delay future promise
    clojure的语法糖
    postgres select TOP X in group 查询每个组的前几名
  • 原文地址:https://www.cnblogs.com/lovling/p/14525021.html
Copyright © 2020-2023  润新知