Java ThreadPoolExecutor의 매개변수 이해

Java ThreadPoolExecutor의 매개변수 이해
1. Executors를 사용하여 스레드 풀 생성
이전에 라인을 만들 때 사용한 Executors의 newFixedThreadPool (), newSingleThreadExecutor (), newCachedThreadPool () 세 가지 방법입니다.물론 Executors도 다른 매개 변수로 new ThreadPoolExecutor를 제거합니다.
    1. newFixedThreadPool()
스레드 수가 고정된 크기의 스레드 탱크를 만듭니다.LinkedBlockingQueue를 사용했기 때문에 maximumPoolSize는 쓸모가 없습니다. 코어PoolSize가 가득 차면 LinkedBlockingQueue 대기열에 추가합니다.어떤 루틴이 실행될 때마다 링크드블록킹Queue 대기열에서 하나를 찾습니다.그래서 이것은 고정된 크기의 스레드 탱크를 만드는 것입니다.

 public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                   0L, TimeUnit.MILLISECONDS,
                   new LinkedBlockingQueue<Runnable>());
  }
 public ThreadPoolExecutor(int corePoolSize,
               int maximumPoolSize,
               long keepAliveTime,
               TimeUnit unit,
               BlockingQueue<Runnable> workQueue) {
   this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
       Executors.defaultThreadFactory(), defaultHandler);
  }
   2.newSingleThreadPool()
스레드 수가 1인 스레드 풀을 만듭니다. LinkedBlockingQueue를 사용했기 때문에 maximumPoolSize는 쓸모가 없습니다. 코어PoolSize는 1로 스레드 수의 크기가 1인 것을 나타냅니다. 가득 차면 대기열에 넣고 실행이 끝나면 대기열에서 하나를 찾습니다.

 public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
      (new ThreadPoolExecutor(1, 1,
                  0L, TimeUnit.MILLISECONDS,
                  new LinkedBlockingQueue<Runnable>()));
  }

    3.newCachedThreadPool()
버퍼 가능한 스레드 탱크를 만듭니다.크기 제한이 없습니다.corePoolSize가 0이기 때문에 작업은 SynchronousQueue 대기열에 넣고, SynchronousQueue는 크기만 1로 저장할 수 있기 때문에 즉시 새 라인이 시작됩니다. maxumPoolSize는 Integer이기 때문입니다.MAX_VALUE는 크기가 2147483647이라고 볼 수 있습니다.메모리 크기에 제한을 받다.

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                   60L, TimeUnit.SECONDS,
                   new SynchronousQueue<Runnable>());
  }
public ThreadPoolExecutor(int corePoolSize,
             int maximumPoolSize,
             long keepAliveTime,
             TimeUnit unit,
             BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
       Executors.defaultThreadFactory(), defaultHandler);
  }
  
2. ThreadPoolExecutor를 사용하여 스레드 풀 생성
ThreadPoolExecutor의 구조 함수

 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.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
  }
매개변수:
1,corePoolSize 핵심 스레드 크기, 스레드 수 2, maximumPoolSize 최대 스레드 수, 스레드 수 >= corePoolSize 시 runnable를 workQueue에 넣습니다
3. keep Alive Time은 코어 Pool Size의 빈 라인보다 많은 라인이 유지할 수 있는 최대 시간을 유지합니다.
4. 유닛 시간 단위
5. workQueue 저장 작업의 막힌 대기열
6,threadFactory가 라인을 만드는 공장
7,handler 거부 정책
작업 수행 순서:
1. 코어PoolSize보다 스레드 수가 적을 때 작업을 수행합니다.
2, 코어 풀 크기와 같은 스레드 수가 많고workQueue가 가득 차지 않을 때workQueue에 넣기
3. 스레드 수가 corePoolSize보다 크고 workQueue가 가득 차면 새 작업의 새 스레드가 실행됩니다. 스레드 총수는 maximumPoolSize보다 작습니다.
4. 라인 총수가 maximumPoolSize와 같고workQueue가 가득 찼을 때handler의rejectedExecution을 실행합니다.전략을 거부하는 것이다.
ThreadPoolExecutor는 기본적으로 네 가지 거부 정책을 가지고 있습니다.
        1、ThreadPoolExecutor.AbortPolicy() 이상 RejectedExecutionException 직접 내보내기
        2、ThreadPoolExecutor.CallerRunsPolicy()는 run 메서드를 직접 호출하여 실행을 차단합니다.
        3、ThreadPoolExecutor.DiscardPolicy () 는 나중에 수행된 작업을 직접 폐기합니다.
        4、ThreadPoolExecutor.DiscardOldestPolicy()가 대기열 중대 첫 번째 임무에 버림됨
물론 거부 정책을 쓰기 위해 Rejected ExecutionHandler를 상속할 수 있습니다.

int corePoolSize = 1;
 int maximumPoolSize = 2;
 int keepAliveTime = 10;
// BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
 BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(5);
 ThreadFactory threadFactory = Executors.defaultThreadFactory();
 // 
 //1. 
 RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); 
 RejectedExecutionHandler handler2 = new ThreadPoolExecutor.CallerRunsPolicy();
 RejectedExecutionHandler handler3 = new ThreadPoolExecutor.DiscardPolicy();
 RejectedExecutionHandler handler4 = new ThreadPoolExecutor.DiscardOldestPolicy();

 
 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, handler2);
 
 
 for (int j = 1; j < 15; j++) {
  threadPoolExecutor.execute(new Runnable() {
  
  public void run() {
   
   try {
   System.out.println(Thread.currentThread().getName());
   TimeUnit.SECONDS.sleep(1);
   } catch (InterruptedException e) {
   e.printStackTrace();
   }
   
   
  }
  });
 }
 
 System.out.println(threadPoolExecutor);
 
 }


읽어주셔서 감사합니다. 여러분에게 도움이 되었으면 좋겠습니다. 본 사이트에 대한 지지에 감사드립니다!

좋은 웹페이지 즐겨찾기