자바 다 중 스 레 드 스 레 드 풀 7 개 매개 변수 상세 설명

ThreadPoolExecutor 는 JDK 의 스 레 드 풀 로 이 루어 집 니 다.이 종 류 는 스 레 드 풀 에 필요 한 여러 가지 방법 을 실현 하고 작업 제출,스 레 드 관리,모니터링 등 방법 을 제공 합 니 다.
다음은 Thread PoolExecutor 류 의 구조 방법 소스 코드 입 니 다.다른 스 레 드 탱크 를 만 드 는 방법 은 최종 적 으로 이 구조 방법 을 안내 합 니 다.모두 7 개의 매개 변수 가 있 습 니 다.core PoolSize,maximum PoolSize,keepAliveTime,unit,work Queue,threadFactory,handler.

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
이 매개 변 수 는 모두 volatile 을 통 해 수식 합 니 다.

public class ThreadPoolExecutor extends AbstractExecutorService {
    private final BlockingQueue<Runnable> workQueue;
    private volatile ThreadFactory threadFactory;
    private volatile RejectedExecutionHandler handler;
    private volatile long keepAliveTime;
    //            
    private volatile boolean allowCoreThreadTimeOut;
    private volatile int corePoolSize;
    private volatile int maximumPoolSize;
}
core PoolSize:핵심 스 레 드 수
스 레 드 탱크 유지 보수 의 최소 스 레 드 수량,핵심 스 레 드 생 성 후 회수 되 지 않 습 니 다(주의:allowCoreThreadTimeout=true 설정 후 남 은 핵심 스 레 드 가 생존 시간 을 초과 해도 회수 합 니 다).
핵심 스 레 드 보다 큰 스 레 드 는 남 은 시간 이 keepAliveTime 을 초과 하면 회수 합 니 다.
스 레 드 탱크 가 처음 만 들 어 졌 을 때,안에 스 레 드 가 하나 도 없 었 습 니 다.execute()방법 으로 작업 을 추가 할 때,실행 중인 스 레 드 수가 corePoolSize 보다 적 으 면 바로 새 스 레 드 를 만 들 고 이 작업 을 실행 합 니 다.
maximumPoolSize:최대 스 레 드 수
스 레 드 탱크 에서 만 들 수 있 는 최대 스 레 드 수 입 니 다.
작업 을 추가 할 때 핵심 스 레 드 가 가득 찼 습 니 다.스 레 드 탱크 는 최대 스 레 드 에 이 르 지 못 했 고 빈 스 레 드 가 없습니다.작업 대기 열 이 가득 찬 상태 에서 새 스 레 드 를 만 든 다음 작업 대기 열의 머리 에서 작업 을 꺼 내 새 스 레 드 에 맡 기 고 방금 제출 한 작업 을 작업 대기 열 끝 에 넣 습 니 다.
keepAliveTime:남 은 스 레 드 생존 시간
재 활용 가능 한 스 레 드 의 남 은 시간 이 keepAliveTime 보다 많 으 면 재 활용 된다.
회수 가능 한 라인:
allowCoreThreadTimeout=true 의 핵심 스 레 드 를 설정 합 니 다.핵심 스 레 드 보다 큰 스 레 드(비 핵심 스 레 드).
시간 단위
keepAliveTime 의 시간 단위:

TimeUnit.NANOSECONDS
TimeUnit.MICROSECONDS
TimeUnit.MILLISECONDS //   
TimeUnit.SECONDS
TimeUnit.MINUTES
TimeUnit.HOURS
TimeUnit.DAYS
작업 대기 열
새 작업 이 제출 되면 작업 대기 열 에 먼저 추가 되 고 작업 스케줄 링 시 대기 열 에서 작업 을 꺼 냅 니 다.작업 대기 열 이 BlockingQueue 인 터 페 이 스 를 실현 하 였 습 니 다.
JDK 의 기본 작업 대기 열 은 다섯 가지 입 니 다.
1.Array BlockingQueue 배열 형 차단 대기 열:배열 구조,초기 화 시 들 어 오 는 크기,경계,FIFO,재 입 자 물 쇠 를 사용 합 니 다.기본적으로 불공평 한 자 물 쇠 를 사용 합 니 다.입 대 는 팀 과 함께 하나의 자 물 쇠 를 사용 하고 서로 배척 합 니 다.
2。링크 드 BlockingQueue 링크 형 차단 대기 열:링크 구조,기본 크기 는 Integer.MAX 입 니 다.VALUE,유 계(근사 무 해),FIFO,두 개의 재 입 자 물 쇠 를 사용 하여 각각 원소 의 입 대 와 출 대 를 제어 하고 Condition 으로 라인 간 의 각성 과 기 다 립 니 다.
3.SynchronousQueue 동기 화 대기 열:용량 이 0 입 니 다.작업 을 추가 하려 면 추출 작업 을 기 다 려 야 합 니 다.이 대기 열 은 채널 에 해당 하 며 요 소 를 저장 하지 않 습 니 다.
4.Priority BlockingQueue 우선 차단 대기 열:경계 가 없 으 며,기본 값 은 요소 의 자연 순서 로 오름차 순 으로 배열 합 니 다.
5.Delay Queue 지연 대기 열:경계 가 없습니다.요 소 는 만 료 시간 이 있 고 만 료 된 요 소 는 꺼 낼 수 있 습 니 다.
threadFactory:라인 공장
스 레 드 공장 을 만 들 면 스 레 드 이름,스 레 드 번호 등 을 설정 할 수 있 습 니 다.
기본 라인 공장:

  /**
     * The default thread factory
     */
    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;
 
        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }
 
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
handler:정책 거부
스 레 드 탱크 의 스 레 드 수가 가득 찼 고 작업 대기 열 이 제한 되 었 을 때 새로 제출 한 작업 은 거부 정책 으로 처리 합 니 다.거부 정책 을 사용자 정의 할 수 있 습 니 다.거부 정책 은 Rejected ExecutionHandler 인 터 페 이 스 를 실현 해 야 합 니 다.
JDK 의 기본 거부 정책 은 네 가지 가 있 습 니 다.
1.AbortPolicy:작업 을 버 리 고 Rejected Execution Exception 이상 을 던 집 니 다.
2.DiscardPolicy:작업 을 버 리 지만 이상 을 던 지지 않 습 니 다.시스템 의 이상 상 태 를 발견 하지 못 할 수도 있 습 니 다.
3.DiscardOldestPolicy:대기 열의 맨 앞 에 있 는 작업 을 버 리 고 거 부 된 작업 을 다시 제출 합 니 다.
4.CallerRunsPolicy:호출 스 레 드 에서 이 작업 을 처리 합 니 다.
기본 거부 정책:

  /**
     * The default rejected execution handler
     */
    private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();
 
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }
 
        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }
사용자 정의 스 레 드 탱크 도구

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 *        
 *
 * @author    
 * @date 2021/04/11 10:24
 */
public class ThreadPoolFactory {
 
    /**
     *           
     *
     * @param threadName     
     * @return    
     */
    public static ExecutorService createFixedThreadPool(String threadName) {
        AtomicInteger threadNumber = new AtomicInteger(0);
        return new ThreadPoolExecutor(
                //      
                desiredThreadNum(),
                //      
                desiredThreadNum() * 2,
                //         
                60L,
                //           
                TimeUnit.SECONDS,
                //     
                new ArrayBlockingQueue<>(1024),
                //     
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, threadName + "-" + threadNumber.getAndIncrement());
                    }
                },
                //     
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        if (!executor.isShutdown()) {
                            try {
                                //           
                                executor.getQueue().put(r);
                            } catch (Exception e) {
                                //         
                                Thread.currentThread().interrupt();
                            }
                        }
                    }
                });
    }
 
    /**
     *       ,   2 cpu   
     */
    public static int desiredThreadNum() {
        return Runtime.getRuntime().availableProcessors() * 2;
    }
}
자바 다 중 스 레 드 풀 의 7 개 매개 변수 에 대한 상세 한 설명 은 여기까지 입 니 다.더 많은 자바 스 레 드 풀 에 대한 상세 한 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!

좋은 웹페이지 즐겨찾기