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);
        }
    }
}
posted on 2021-03-12 17:04  被遗忘的优雅  阅读(120)  评论(0编辑  收藏  举报