> Java > java지도 시간 > 본문

Java에서 ThreadPoolExecutor 동시 호출에 대한 예제 코드 분석

黄舟
풀어 주다: 2017-05-28 09:11:13
원래의
2037명이 탐색했습니다.

이 글은 Java ThreadPoolExecutor 동시 호출 인스턴스에 대한 자세한 설명을 중심으로 소개하고 있으니 필요하신 분들은 참고하시면 됩니다.

Java ThreadPoolExecutor 동시 호출 인스턴스에 대한 자세한 설명

개요

일반적으로 작업의 처리 속도를 향상시키기 위해 ThreadPoolExecutor에서 일부 동시성 모델 을 사용하고 informAll을 사용하는 것이 하나입니다.

Code

package test.current;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class TestCallable {

  public static void main(String[] args) throws InterruptedException, ExecutionException {

    List<Callable<List<Long>>> tasks = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      Callable<List<Long>> task = new Callable<List<Long>>() {
        @Override
        public List<Long> call() throws Exception {
          return Arrays.asList(1L,2L);
        }
      };

      tasks.add(task);
    }

    List<Long> finalResults = new ArrayList<>(10);
    List<Future<List<Long>>> results = ThreadPool.getThreadPool().invokeAll(tasks);
    for(Future<List<Long>> ele : results) {
      List<Long> list = ele.get();
      finalResults.addAll(list);
    }

    System.out.println(finalResults);
  }
}
로그인 후 복사
package test.current;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
  private static final int CORE_SIZE = 8;

  private static final int MAX_SIZE = 12;

  private static final long KEEP_ALIVE_TIME = 30;

  private static final int QUEUE_SIZE = 50000;

  private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_TIME,
      TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());

  public static ThreadPoolExecutor getThreadPool() {
    return threadPool;
  }
}
로그인 후 복사

는 실행해야 하는 작업에 대해 Callable 작업을 생성하고 스레드 풀의 스레드를 사용하여 이러한 작업을 동시에 실행함으로써 작업의 실행 효율성을 향상시킬 수 있습니다.

위 내용은 Java에서 ThreadPoolExecutor 동시 호출에 대한 예제 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!