Java의 ExecutorService는 무엇이며 어떻게 생성합니까?



이 기사에서는 Java의 스레드 생성 및 관리를 설명하는 다양한 예제와 함께 Java의 Executor 하위 인터페이스 ExecutorService의 개념을 다룹니다.

Java 프로그래밍 언어는 작업이 스레드에서 동시에 실행되어야하는 애플리케이션. 모든 응용 프로그램에서 동시에 많은 수의 스레드를 실행하기가 어려워집니다. 그래서이 문제를 극복하기 위해 의 하위 인터페이스 인 ExecutorService와 함께 제공됩니다. . 이 기사에서는 Java에서 ExecutorService의 기능에 대해 설명합니다. 이 블로그에서 다루는 주제는 다음과 같습니다.

Executor Framework 란 무엇입니까?

동시에 하나 또는 두 개의 스레드를 만들고 실행하는 것이 훨씬 쉽습니다. 그러나 쓰레드 수가 상당히 증가하면 어려워집니다. 대규모 다중 스레드 응용 프로그램에는 수백 개의 스레드가 동시에 실행됩니다. 따라서 응용 프로그램의 스레드 관리에서 스레드 생성을 분리하는 것이 합리적입니다.





집행자는 응용 프로그램에서 스레드를 만들고 관리하는 데 도움이됩니다. 그만큼 다음 작업에 도움이됩니다.

  • 스레드 생성 : 애플리케이션을 동시에 실행하는 데 도움이되는 스레드 생성을위한 다양한 방법을 제공합니다.



  • 스레드 관리 : 스레드 수명 주기도 관리합니다. 실행을 위해 작업을 제출하기 전에 스레드가 활성 상태인지, 사용 중인지 또는 죽었는지 걱정할 필요가 없습니다.

  • 작업 제출 및 실행 : Executor 프레임 워크는 스레드 풀에서 작업 제출을위한 메서드를 제공하며 스레드 실행 여부를 결정할 수있는 권한도 제공합니다.

java -edureka의 executorservice-executorservice

Java 예제의 ExecutorService

애플리케이션의 스레드 수명주기를 관리하기 위해 특정 기능을 추가하는 실행기 프레임 워크의 하위 인터페이스입니다. 또한 실행 가능 및 호출 가능을 모두 허용 할 수있는 submit () 메소드를 제공합니다. 사물.



다음 예제에서는 단일 스레드로 ExecutorService를 만든 다음 스레드 내에서 실행할 작업을 제출합니다.

import java.util.concurrent.ExecutorService import java.util.concurrent.Executors public class 예제 {public static void main (String [] args) {System.out.println ( 'Inside :'+ Thread.currentThread (). getName ( )) System.out.println ( 'creating ExecutorService') ExecutorService executorservice = Executors.newSingleThreadExecutor () System.out.println ( 'creating a runnable') Runnable runnable = ()-> {System.out.println ( 'inside : '+ Thread.currentThread (). getName ())} System.out.println ('실행 파일에서 지정한 작업을 executorservice에 제출 ') executorservice.submit (runnable)}}
 산출: 내부 : 메인 생성 ExecutorService 실행 파일 생성 실행 파일에서 지정한 작업을 내부 executorservice에 제출합니다. pool-1-thread-1

위 ExecutorService를 생성하고 실행기 내에서 태스크를 실행하는 방법을 보여줍니다. 작업이 실행을 위해 제출되고 스레드가 현재 다른 작업을 실행중인 경우 작업은 스레드가 실행할 수있을 때까지 대기열에서 대기합니다.

위의 프로그램을 실행하면 프로그램이 종료되지 않습니다. 실행기 서비스가 새 작업을 계속 수신하므로 명시 적으로 종료해야합니다.

Java ExecutorService 구현

ExecutorService는 스레드 풀과 매우 유사합니다. 사실, java.util.concurrent에서 ExecutorService의 구현은 꾸러미 스레드 풀 구현입니다. ExecutorService는 java.util.concurrent 패키지에 다음 구현을 포함합니다.

ThreadPoolExecutor

ThreadPoolExecutor는 내부적으로 풀링 된 스레드 중 하나를 사용하여 주어진 작업을 실행합니다.

threadPoolExecutor 만들기

int corePoolSize = 5 int maxPoolSize = 10 long keepAliveTime = 5000 ExecutorService threadPoolExecutor = new threadPoolExecutor (corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue ())

ScheduledThreadPoolExecutor

java.util.concurrent.ScheduledThreadPoolExecutor는 지연 후 실행되거나 각 실행 사이에 고정 된 시간 간격으로 반복적으로 실행되도록 태스크를 스케줄 할 수있는 ExecutorService입니다.

ScheduledExecutorService Scheduledexecutorservice = Executors.newScheduledThreadPool (5) ScheduledFuture schedulefuture = scheduleExecutorService.schedule (new Callable () {public Object call () throws Exception {System.out.println ( 'executed') return 'called'}}, 5, TimeUnit. SECONDS)

ExecutorService 사용

ExecutorService에 작업을 위임하는 몇 가지 방법이 있습니다.

  • execute (실행 가능)

  • 제출 (실행 가능)

  • invokeAny ()

  • invokeAll ()

Runnable 실행

Java ExecutorService execute (Runnable)는 java.lang.Runnable 객체를 가져 와서 비동기 적으로 실행합니다.

ExecutorService executorService = Executors.newSingleThreadExecutor () executorService.execute (new Runnable () {public void run () {System.out.println ( 'asynchronous task')}}) executorService.shutdown ()

Callable을 사용해야하기 때문에 Runnable 실행의 결과를 얻을 수있는 방법이 없습니다.

실행 가능 제출

Java ExecutorService submit (Runnable) 메소드는 Runnable 구현을 취하고 미래 객체를 반환합니다. Future 객체는 Runnable이 실행을 완료했는지 확인하는 데 사용할 수 있습니다.

Future future = executorService.submit (new Runnable () {public void run () {System.out.println (: asynchronous task ')}}) future.get () // 작업이 올바르게 완료되면 null을 반환합니다.

호출 가능 제출

Java ExecutorService submit (Callable) 메소드는 submit (Runnable)과 유사하지만 Runnable 대신 Java Callable을 사용합니다.

Future future = executorService.submit (new Callable () {public Object call () throws Exception {System.out.println ( 'Asynchronous callable') return 'Callable Result'}}) System.out.println ( 'future.get ( ) = 'future.get ())
 산출: 비동기 호출 가능 future.get = 호출 가능 결과

invokeAny ()

invokeAny () 메서드는 Callable 개체의 컬렉션을받습니다. 이 메서드를 호출하면 future는 반환되지 않지만 Callable 개체 중 하나의 결과가 반환됩니다.

ExecutorService executorService = Executors.newSingleThreadExecutor () 세트콜 러블 = 새로운 HashSet() callables.add (new Callable () {public String call () throws Exception {return'task A '}}) callables.add (new Callable () {public String call () throws Exception {return'task B'} }) callables.add (new Callable () {public String call () throws Exception {return'task C '}}) String result = executorService.invokeAny (callables) System.out.println ('result = '+ result) executorService .일시 휴업()

위의 코드를 실행하면 결과가 변경됩니다. 태스크 A, 태스크 B 등이 될 수 있습니다.

InvokeAll ()

invokeAll () 메서드는 매개 변수로 전달 된 모든 Callable 객체를 호출합니다. 각 Callable의 실행 결과를 얻는 데 사용할 수있는 미래 객체를 반환합니다.

ExecutorService executorService = Executors.newSingleThreadExecutor () 세트콜 러블 = 새로운 HashSet() callables.add (new Callable () {public String call () throws Exception {return 'Task A'}}) callables.add (new Callable () {public String call () throws Exception {return 'Task B'} }) callables.add (new Callable () {public String call () throws Exception {return 'Task C'}}) 목록futures = executorService.invokeAll (callables) for (Future future : futures) {System.out.println ( 'future.get ='+ future.get ())} executorService.shutdown ()

실행 가능 vs 호출 가능

실행 가능한 인터페이스와 호출 가능한 인터페이스는 서로 매우 유사합니다. 차이점은 인터페이스. 두 인터페이스 모두 스레드 또는 ExecutorService에서 동시에 실행할 수있는 작업을 나타냅니다.

호출 가능 선언 :

public interface Callable {public object call () throws Exception}

실행 가능 선언 :

공용 인터페이스 Runnable {public void run ()}

이 둘의 주요 차이점은 call () 메서드가 메서드 호출에서 객체를 반환 할 수 있다는 것입니다. 그리고 call () 메소드는 run () 메소드는 할 수 없습니다.

대학원 졸업장 대 석사

작업 취소

태스크가 제출 될 때 제출 된 미래에 cancel 메소드를 호출하여 ExecutorService에 제출 된 태스크를 취소 할 수 있습니다.

future.cancel ()

ExecutorService 종료

실행이 완료된 후에도 스레드가 실행되지 않도록하려면 ExecutorService를 종료해야합니다.

일시 휴업()

ExecutorService 내부의 스레드를 종료하려면 shutdown () 메서드를 호출 할 수 있습니다.

executorService.shutdown ()

이것으로 ExecutorService를 사용하여 스레드에서 작업을 실행하는 방법을 배운이 기사의 끝으로 이동합니다. 이 튜토리얼에서 여러분과 공유 한 모든 내용이 명확하기를 바랍니다.

'ExecutorService in Java'관련 기사를 찾았다면 전 세계에 250,000 명 이상의 만족 한 학습자 네트워크를 보유한 신뢰할 수있는 온라인 학습 회사입니다.

우리는 여정의 모든 단계에서 귀하를 돕고 Java 개발자가 되고자하는 학생과 전문가를 위해 설계된 커리큘럼을 마련합니다. 이 과정은 Java 프로그래밍을 시작하고 다양한 Java 개념과 함께 핵심 및 고급 Java 개념을 교육하도록 설계되었습니다. 처럼 최대 절전 모드 & .

질문이 있으시면 'ExecutorService in Java'의 코멘트 섹션에 모든 질문을 남겨 주시면 저희 팀이 기꺼이 답변 해 드리겠습니다.