스레드 풀을 소개하는 1 가지 이유
스레드의 수명주기에는 생성, 준비, 달리기, 차단 및 단계가 포함되므로 계류중인 작업의 수가 적을 때는 해당 작업을 처리하기 위해 여러 스레드를 만들 수 있지만 많은 숫자가있을 때는 여러 스레드를 만들 수 있습니다. 작업의 경우 스레드를 작성하고 파괴하려면 많은 오버 헤드가 필요하며 스레드 풀을 사용하면 이러한 문제가 크게 완화됩니다.
2 스레드 풀 사용
해당 스레드 풀을 만들기 위해 Executors 클래스가 제공 한 정적 메소드 만 사용하면됩니다.
public static executorsvice newsinglethreadexecutor () public static executorsvice newfixedthreadpool () public static executorsvice newCachedthre adpool ()
NewsingLethreadExecutor 단일 스레드가 포함 된 집행자를 반환하면 스레드가 하나의 작업을 처리 한 다음 스레드에서 예외가 발생합니다.
NewFixedThreadpool 지정된 스레드가 포함 된 스레드 풀을 반환합니다. 작업 수가 스레드 수보다 더 많으면 작업이 완료 될 때까지 대기하지 않아야합니다.
NewCachedThreadPool이 스레드 풀의 수를 기반으로 해당 스레드를 생성하면 스레드 수를 제한하지 않으며 JVM이 생성 할 수있는 스레드 수에 달려 있습니다.
작업을 실행 메소드에 실행하고 실행 가능한 인터페이스의 구현 클래스를 아래에 표시된 것처럼 매개 변수로 스레드 풀의 실행 메소드에 전달하면됩니다.
Executor Executor = Executor.NewsingLethreadExecutor (); Executor.Execute (New Runnable () {public void Run () {// executed tasks}}매개 변수를 작업에 전달 해야하는 경우, 실행 가능한 인터페이스에 대한 구현 클래스를 만들어이를 수행 할 수 있습니다.
3. 예
(1) : NewsingLethreadExecutor
Mythread.java
publicclassmythread는 {@override publicvoid run () {system.out.println (thread.currentthread (). getName () + "execution ...")를 확장합니다. {// 고정 된 수의 스레드를 재사용 할 수 있습니다. 스레드 T2 = 스레드 T3 = 스레드 (); pool.execu te (t2). 출력 결과
풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . .
(2) : NewFixedThreadpool
testfixedthreadpool.java
publicclass testfixedthreadpool {publicstaticvoid main (String [] args) {// 고정 된 수의 스레드를 재사용 할 수있는 스레드 풀을 만듭니다. 런닝 가능한 스레드 T1 = 스레드 T2 = 새로운 Mythread (); 수영장 실행 (T1). }} 출력 결과
풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -2가 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -2가 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . .
(3) : NewCachedthreadpool
testCachedThreadpool.java
publicclass testCachedThreadPool {publicStaticVoid main (String [] args) {// 고정 된 수의 실행 수영장을 생성합니다. 런닝 가능한 스레드 T1 = 스레드 () 실행 (T1). } 출력 결과 :
풀 -1- 스레드 -2가 실행 중입니다. . . Pool-1-Shread-4가 실행 중입니다. . . Pool-1-Shread-3이 실행 중입니다. . . 풀 -1- 스레드 -1이 실행 중입니다. . . 풀 -1- 스레드 -5가 실행 중입니다. . .
(4) : NewsCheduledthreadpool
TestScheduledthreadpoolexecutor.java
publicclass testscheduledthreadpoolexecutor {publicstaticVoid main (string [] args) {scheduledtheRreadPooleExecutor exec = new ScheduledThreadPooleExecut tor (1); 새로운 runtimeexception ()을 던지십시오 =================================================== ============= runna ble () {// 시스템 시간을 가끔씩 인쇄하여 두 사람이 서로 @override publicvoid run () {system.out.println에 영향을 미치지 않음을 증명합니다. (System.nanoTime ()), 1000, 2000, TimeUnit.milliseconds); 출력 결과
=================================================== =================================================== =================================================== =================================================== =================================================== =====