>  기사  >  Java  >  Java의 스레드 풀

Java의 스레드 풀

WBOY
WBOY원래의
2023-06-15 20:51:481366검색

Java에서 스레드 풀은 스레드 생성, 유지 관리, 삭제와 같은 작업을 관리하는 데 사용됩니다. 스레드 풀에는 스레드 그룹과 작업 대기열이 포함되어 있습니다. 작업을 실행해야 할 경우 스레드 풀의 스레드는 자동으로 작업을 가져와 실행합니다. 재사용을 위한 스레드 풀.

Java의 스레드 풀 API는 스레드 풀을 생성하는 데 도움이 되는 Executors 클래스를 제공하고, 4가지 스레드 풀 구현 방법(FixedThreadPool, CachedThreadPool, SingleThreadExecutor 및 ScheduledThreadPool)을 제공합니다.

FixedThreadPool

고정 크기 스레드 풀입니다. 작업 스레드 수가 스레드 풀 크기에 도달하지 못한 경우에만 작업을 수행하기 위해 새 스레드가 생성됩니다. 스레드 풀은 생성자를 통해 최대 스레드 수를 지정할 수 있습니다. 지정하지 않으면 기본값은 Integer.MAX_VALUE입니다.

샘플 코드:

ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
    executorService.execute(()->{
        System.out.println(Thread.currentThread().getName()+" is executing task ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

실행 결과:

pool-1-thread-1 is executing task 
pool-1-thread-3 is executing task 
pool-1-thread-5 is executing task 
pool-1-thread-2 is executing task 
pool-1-thread-4 is executing task 
pool-1-thread-5 is executing task 
pool-1-thread-3 is executing task 
pool-1-thread-1 is executing task 
pool-1-thread-2 is executing task 
pool-1-thread-4 is executing task 

CachedThreadPool

캐시 가능한 스레드 풀이 현재 필요한 수를 초과하면 초과 스레드는 스레드 풀로 재활용됩니다. 자동으로 폐기됩니다. 스레드 풀에 사용 가능한 스레드가 없고 새 작업이 도착하면 스레드 풀은 스레드 풀 크기가 Integer.MAX_VALUE 제한에 도달할 때까지 작업을 실행하기 위해 새 스레드를 생성합니다.

샘플 코드:

ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
    executorService.execute(()->{
        System.out.println(Thread.currentThread().getName()+" is executing task ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

실행 결과:

pool-1-thread-1 is executing task 
pool-1-thread-2 is executing task 
pool-1-thread-3 is executing task 
pool-1-thread-4 is executing task 
pool-1-thread-5 is executing task 
pool-1-thread-6 is executing task 
pool-1-thread-7 is executing task 
pool-1-thread-8 is executing task 
pool-1-thread-9 is executing task 
pool-1-thread-10 is executing task 

SingleThreadExecutor

단 하나의 작업자 스레드가 있는 단일 스레드 스레드 풀은 모든 작업이 지정된 순서(FIFO, LIFO, 우선 순위 등)로 실행되도록 보장할 수 있습니다. , 이는 특수 FixThreadPool과 동일합니다.

샘플 코드:

ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
    executorService.execute(()->{
        System.out.println(Thread.currentThread().getName()+" is executing task ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

실행 결과:

pool-1-thread-1 is executing task 
pool-1-thread-1 is executing task 
pool-1-thread-1 is executing task
......

ScheduledThreadPool

예약된 스레드 풀은 지정된 지연 시간에 따라 또는 주기적으로 작업을 실행할 수 있으며 예약된 작업 또는 주기적 작업을 구현할 수 있습니다. 스레드 풀의 크기를 지정할 수 있습니다. 지정하지 않으면 기본값은 Integer.MAX_VALUE입니다.

샘플 코드:

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
ScheduledFuture<?> future = scheduledExecutorService.schedule(()->{
    System.out.println(Thread.currentThread().getName()+" is executing delay task ");
}, 5, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(()->{
    System.out.println(Thread.currentThread().getName()+" is executing periodic task ");
}, 2, 3, TimeUnit.SECONDS);

실행 결과:

pool-1-thread-1 is executing periodic task 
pool-1-thread-2 is executing periodic task 
pool-1-thread-3 is executing periodic task 
pool-1-thread-1 is executing periodic task 
pool-1-thread-3 is executing periodic task 
pool-1-thread-2 is executing periodic task 
pool-1-thread-3 is executing periodic task 
pool-1-thread-2 is executing periodic task 
......
pool-1-thread-1 is executing delay task 

요약

스레드 풀은 멀티 스레드 개발에서 매우 중요한 개념으로, 스레드 생성, 삭제 및 컨텍스트 전환의 오버헤드를 효과적으로 줄이고 시스템 성능 및 유지 관리 가능성을 향상시킬 수 있습니다. . Java는 스레드 풀을 쉽게 생성할 수 있는 Executors 클래스를 제공하고 다양한 애플리케이션 시나리오를 처리하기 위한 다양한 구현 방법을 제공합니다. 개발자가 스레드 풀을 사용할 때 최상의 성능과 효과를 얻으려면 특정 요구 사항과 로드 조건에 따라 적절한 구현 방법을 선택해야 합니다.

위 내용은 Java의 스레드 풀의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.