Java에서 동시에 여러 스레드를 실행하는 방법은 무엇입니까? ExecutorService 접근 방식
게시 됨: 2021-10-09
이 예를 다시 살펴보겠습니다. Java에서 HTTP 끝점의 Ping 상태를 얻는 방법은 무엇입니까?
해당 예제의 스레드 실행을 보았습니까? 순차적입니다. What if you have 500 endpoints?
결과를 얻으려면 최소 5분을 기다려야 합니다. 내가 확신하는 것은 최선의 해결책이 아닙니다.
이제 뭐? 올바른 질문은 다음과 같습니다.
- 여러 스레드를 동시에 실행하는 방법은 무엇입니까?
- Java에서 다중 스레드를 구현하는 방법은 무엇입니까?
- Java에서 다른 스레드를 어떻게 실행합니까?
- Java – 멀티스레딩 프로그래밍 자습서는 어디에 있습니까?
- 스레드: 처리 속도를 높이기 위해 여러 스레드를 사용하는 방법은 무엇입니까?
ExecutorService Approach
이 답입니다.
종료를 관리하는 메서드와 하나 이상의 비동기 작업의 진행 상황을 추적하기 위해 Future를 생성할 수 있는 메서드를 제공하는 Executor입니다.
ExecutorService는 종료될 수 있으며 이로 인해 새 작업이 거부됩니다. ExecutorService를 종료하기 위해 두 가지 다른 방법이 제공됩니다. shutdown()
메서드는 이전에 제출된 작업이 종료되기 전에 실행되도록 허용하는 반면, shutdownNow()
메서드는 대기 중인 작업이 시작되는 것을 방지하고 현재 실행 중인 작업을 중지하려고 시도합니다.
종료 시 실행자는 활성 실행 중인 작업, 실행 대기 중인 작업 및 제출할 수 있는 새 작업이 없습니다. 사용하지 않는 ExecutorService는 리소스를 회수할 수 있도록 종료되어야 합니다.
메소드 제출은 실행을 취소하거나 완료를 기다리는 데 사용할 수 있는 Future를 생성하고 반환하여 기본 메소드 Executor.execute
( java.lang.Runnable
)를 확장합니다. invokeAny
및 invokeAll
메소드는 가장 일반적으로 유용한 대량 실행 형식을 수행하여 작업 모음을 실행한 다음 적어도 하나 또는 모두가 완료될 때까지 기다립니다. (클래스 ExecutorCompletionService를 사용하여 이러한 메서드의 사용자 정의된 변형을 작성할 수 있습니다.)
Executors 클래스는 이 패키지에서 제공되는 실행기 서비스에 대한 팩토리 메소드를 제공합니다.
- java – ExecutorService, 모든 작업이 완료될 때까지 어떻게 기다리나요?
- Java ExecutorService 가이드
- 자바 쓰레드 풀 – ExecutorService 설명
다음은 usage of ExecutorService
을 설명하는 간단한 Java 예제입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
package crunchify . com . tutorials ; import java . net . HttpURLConnection ; import java . net . URL ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; /** * @author Crunchify.com * How to Run Multiple Threads Concurrently in Java? ExecutorService Approach. */ public class CrunchifyGetPingStatusWithExecutorService { private static final int crunchifyThreads = 30 ; public static void main ( String [ ] args ) throws Exception { // Executors: Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. // ExecutorService: An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks. // An ExecutorService can be shut down, which will cause it to reject new tasks. // Two different methods are provided for shutting down an ExecutorService. // The shutdown method will allow previously submitted tasks to execute before terminating, while the shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks. // Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. // An unused ExecutorService should be shut down to allow reclamation of its resources. ExecutorService executor = Executors . newFixedThreadPool ( crunchifyThreads ) ; // newFixedThreadPool(): Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. // At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. // If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks String [ ] crunchifyList = { "https://crunchify.com" , "https://yahoo.com" , "https://www.ebay.com" , "https://google.com" , "https://www.example.co" , "https://paypal.com" , "http://bing.com/" , "https://techcrunch.com/" , "http://mashable.com/" , "https://pro.crunchify.com/" , "https://wordpress.com/" , "https://wordpress.org/" , "https://example.com/" , "https://sjsu.edu/" , "https://ask.crunchify.com/" , "https://test.com.au/" , "https://www.wikipedia.org/" , "https://en.wikipedia.org" } ; for ( int i = 0 ; i < crunchifyList . length ; i ++ ) { String url = crunchifyList [ i ] ; Runnable worker = new MyRunnable ( url ) ; // execute(): Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, // or in the calling thread, at the discretion of the Executor implementation. executor . execute ( worker ) ; } // shutdown(): Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. // Invocation has no additional effect if already shut down. // This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that. executor . shutdown ( ) ; // Wait until all threads are finish // Returns true if all tasks have completed following shut down. // Note that isTerminated is never true unless either shutdown or shutdownNow was called first. while ( ! executor . isTerminated ( ) ) { // empty body } System . out . println ( "\nFinished all threads" ) ; } // Runnable: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. // The class must define a method of no arguments called run. public static class MyRunnable implements Runnable { private final String url ; MyRunnable ( String url ) { this . url = url ; } @Override public void run ( ) { String result = "" ; int code = 200 ; try { URL siteURL = new URL ( url ) ; // HttpURLConnection: A URLConnection with support for HTTP-specific features. See the spec for details. // openConnection(): Returns a URLConnection instance that represents a connection to the remote object referred to by the URL. HttpURLConnection connection = ( HttpURLConnection ) siteURL . openConnection ( ) ; // setRequestMethod: Set the method for the URL request, one of: //GET //POST //HEAD //OPTIONS //PUT //DELETE //TRACE connection . setRequestMethod ( "GET" ) ; // setConnectTimeout(): Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. // If the timeout expires before the connection can be established, a java.net connection . setConnectTimeout ( 3000 ) ; // connect(): Opens a communications link to the resource referenced by this URL, if such a connection has not already been established. connection . connect ( ) ; // getResponseCode(): Gets the status code from an HTTP response message. For example, in the case of the following status lines: // HTTP/1.0 200 OK // HTTP/1.0 401 Unauthorized code = connection . getResponseCode ( ) ; if ( code == 200 ) { result = "-> Green <-\t\t" + "Code: " + code ; ; } else { result = "-> Yellow <-\t\t" + "Code: " + code ; } } catch ( Exception e ) { result = "-> Red <-\t\t" + "Wrong domain - Exception: " + e . getMessage ( ) ; } System . out . println ( url + "\t\t\t\tStatus:" + result ) ; } } } |
산출:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/ Users / app / . m2 / repository / org / slf4j / slf4j - api / 1.7.31 / slf4j - api - 1.7.31.jar : / Users / app / . m2 / repository / org / slf4j / jul - to - slf4j / 1.7.31 / jul - to - slf4j - 1.7.31.jar : / Users / app / . m2 / repository / org / slf4j / jcl - over - slf4j / 1.7.31 / jcl - over - slf4j - 1.7.31.jar : / Users / app / . m2 / repository / org / slf4j / log4j - over - slf4j / 1.7.31 / log4j - over - slf4j - 1.7.31.jar crunchify . com . tutorials . CrunchifyGetPingStatusWithExecutorService http : //mashable.com/ Status:-> Yellow <- Code: 301 http : //bing.com/ Status:-> Green <- Code: 200 https : //www.example.co Status:-> Red <- Wrong domain - Exception: www.example.co https : //example.com/ Status:-> Green <- Code: 200 https : //wordpress.com/ Status:-> Green <- Code: 200 https : //www.wikipedia.org/ Status:-> Green <- Code: 200 https : //test.com.au/ Status:-> Yellow <- Code: 301 https : //wordpress.org/ Status:-> Green <- Code: 200 https : //techcrunch.com/ Status:-> Green <- Code: 200 https : //www.ebay.com Status:-> Green <- Code: 200 https : //ask.crunchify.com/ Status:-> Green <- Code: 200 https : //en.wikipedia.org Status:-> Green <- Code: 200 https : //crunchify.com Status:-> Green <- Code: 200 https : //sjsu.edu/ Status:-> Green <- Code: 200 https : //pro.crunchify.com/ Status:-> Green <- Code: 200 https : //google.com Status:-> Green <- Code: 200 https : //paypal.com Status:-> Green <- Code: 200 https : //yahoo.com Status:-> Green <- Code: 200 Finished all threads Process finished with exit code 0 |
이제 결과를 확인하십시오.
단 몇 초 안에 완료되어야 합니다. 도움이 되셨기를 바랍니다. 이것을 한 번 이상 실행하면 모든 스레드가 병렬로 실행되므로 다른 결과를 볼 수 있으며 빠른 결과를 얻은 사람은 Eclipse 콘솔에 게시된 결과를 볼 수 있습니다.
모든 쿼리에 대해 알려주십시오.