Java 스레드 풀의 여러 구현 방법 및 차이점 소개
import java.text.dateformat; import java.text.simpledateformat; import java.util.arraylist; import java.util.date; import java.util.list; import java.util.list; import java.util.concurrent.callable; import java.util.concurrent.current. java.util.concurrent.executors; import java.util.concurrent.future; public class testthreadpool {// -newfixedthreadpool {// newfixedthreadpool은 Cachethreadpool과 유사하며 재사용이라면 언제든지 새 스레드를 생성 할 수 없지만, 유제품이 될 수는 없습니다. 이 시점에서 새로운 스레드가 설정되어 있다면 다른 대기열에만 배치 될 수 있고 현재 스레드의 스레드가 직접 종료되어 직접 풀에서 옮겨 질 때까지 기다릴 수 있습니다. //- Cachethreadpool과 달리, FixedThreadpool은 유휴 메커니즘을 가지고 있지 않지만, 문서가 언급되어 있지 않기 때문에 TCP와 유사해야합니다. FixedThreadpool은 주로 매우 안정적이고 고정 된 정기적 인 동시 스레드를 목표로하며, 주로 서버에서 사용됩니다. // - 메소드의 소스 코드, 캐시 풀 및 수영장은 동일한 기본 풀을 호출하지만 매개 변수는 다르지만, 고정 풀 스레드 카운트는 고정되어 있으며, 고정 된 풀 스레드 수는 고정되어 있으며, 0 초 유휴 상태입니다. 공차는 전혀 고려되지 않습니다), 60 초 유휴 상태 정적 ExecutorService 고정 서비스 = Executor.NewFixedThreadPool (6); // 캐시 풀, 먼저 풀에 이전에 설정된 스레드가 있는지 확인하십시오. 그렇지 않은 경우 새 스레드를 작성하여 풀에 추가 //- 캐시 풀은 일반적으로 매우 짧은 수명을 가진 비동기적인 작업을 수행하는 데 사용됩니다. 따라서 일부 연결 지향 데몬 유형 서버에서는 많이 사용되지 않습니다. //- 재사용 할 수있는 스레드는 타임 아웃 유휴 내에서 풀의 스레드 여야합니다. 기본 시간 초과는 60 대입니다. 유휴 시간이 지속 시간을 초과하면 스레드 인스턴스가 종료되어 수영장 밖으로 이동합니다. // 캐시드 스레드 풀에 넣는 스레드는 그 끝에 대해 걱정할 필요가 없습니다. 시간 초과 후 비활성화되면 자동으로 종료됩니다. Private STATIC EXECTORSERVICE CACHESERVICE = EXECUTORS.NEWCACHEDTHREADPOOL (); // 싱글 턴 스레드, 언제라도 하나의 스레드 만있을 수 있습니다. // 기본 풀은 캐시 풀 및 고정 풀과 동일하지만 스레드 수는 1-1,0 초 유휴 상태입니다 (유휴 상태 없음) 비공개 정적 ExecutorService SingleService = Executor.NewsingLethreadExecutor (); // -scheduled Thread Pool //-이 풀의 스레드는 일정에 따라 순서대로 지연 될 수 있습니다. public static void main (String [] args) {dateformat format = new SimpledateFormat ( "yyyy-mm-dd hh : mm : ss"); 목록 <integer> customerList = new ArrayList <integer> (); System.out.println (format.format (new Date ()); TestFixedThreadPool (FixedService, CustomerList); System.out.println ( "---------------------------------------------------- TestFixedThreadPool (FixedService, CustomerList); fixedService.shutdown (); System.out.println (고정서 서비스 .Shutdown ()); System.out.println ( "------------------------------------------------------------------------------------------------------------------- TestCachethreadpool (Cacheservice, CustomerList); System.out.println ( "------------------------------------------------------------------------------------------------------------------- TestCachethreadpool (Cacheservice, CustomerList); cacheservice.shutdownnow (); System.out.println ( "------------------------------------------------------------------------------------------------------------------- TestsingLeserViceThreadpool (Singleservice, CustomerList); TestsingLeserViceThreadpool (Singleservice, CustomerList); Singleservice.shutdown (); System.out.println ( "------------------------------------------------------------------------------------------------------------------- TestScheduledservicethreadpool (ScheduledService, CustomerList); TestScheduledservicethreadpool (ScheduledService, CustomerList); ScheduledService.shutdown (); } public static void testscheduledservicethreadpool (ExecutorService Service, List <integer> customerList) {list <Callable <integer >> listCallable = new ArrayList <Callable <integer>> (); for (int i = 0; i <10; i ++) {callable <integer> callable = new Callable <integer> () {@override public integer call () 예외 {return new random (). nextint (10); }}; ListCallable.add (호출 가능); } try {list <future <integer >> listfuture = service.invokeall (listCallable); for (future <integer> future : listfuture) {integer id = future.get (); CustomerList.add (id); }} catch (예외 e) {e.printstacktrace (); } system.out.println (customerList.ToString ()); } public static void testingsingleserviceThreadPool (ExecutOrService Service, List <Integer> CustomerList) {list <Callable <list <integer >>> listCallable = new arrayList <Callable <integer>> (); for (int i = 0; i <10; i ++) {callable <list <integer >>> callable = new Callable <insteger >> () {@override public list <integer> call () 예외 {list <integer> list = getList (new random (). nextInt (10)); 부울 isstop = false; while (list.size ()> 0 &&! isstop) {system.out.println (thread.currentthread (). getId () + " - 수면 : 1000"); isstop = true; } 반환 목록; }}; ListCallable.add (호출 가능); } try {list <future <list <integer >>> listfuture = service.invokeall (listCallable); for (future <list <integer >> future : listfuture) {list <integer> list = future.get (); CustomerList.addall (목록); }} catch (예외 e) {e.printstacktrace (); } system.out.println (customerList.ToString ()); } public static void testCachetHreadPool (ExecutOrService Service, list <integer> customerList) {list <callable <list <integer >>> listCallable = new arrayList <callable <integer>> (); for (int i = 0; i <10; i ++) {callable <list <integer >> affeable = new Callable <insteger >> () {@override public list <integer> call () 예외 {list <integer> list = getList (new random (). nextInt (10)); 부울 isstop = false; while (list.size ()> 0 &&! isstop) {system.out.println (thread.currentthread (). getId () + " - 수면 : 1000"); isstop = true; } 반환 목록; }}; ListCallable.add (호출 가능); } try {list <future <list <integer >>> listfuture = service.invokeall (listCallable); for (future <list <integer >> future : listfuture) {list <integer> list = future.get (); CustomerList.addall (목록); }} catch (예외 e) {e.printstacktrace (); } system.out.println (customerList.ToString ()); } public static void testfixedthreadpool (ExecutorService Service, list <integer> customerList) {list <callable <list <integer >>> listCallable = new arrayList <callable <integer>>> (); for (int i = 0; i <10; i ++) {callable <list <integer >> affeable = new Callable <insteger >> () {@override public list <integer> call () 예외 {list <integer> list = getList (new random (). nextInt (10)); 부울 isstop = false; while (list.size ()> 0 &&! isstop) {system.out.println (thread.currentthread (). getId () + " - 수면 : 1000"); isstop = true; } 반환 목록; }}; ListCallable.add (호출 가능); } try {list <future <list <integer >>> listfuture = service.invokeall (listCallable); for (future <list <integer >> future : listfuture) {list <integer> list = future.get (); CustomerList.addall (목록); }} catch (예외 e) {e.printstacktrace (); } system.out.println (customerList.ToString ()); } public static list <integer> getList (int x) {list <integer> list = new ArrayList <integer> (); list.add (x); list.add (x * x); 반환 목록; }}사용 : LinkedBlockingqueue 스레드 풀 설명을 구현합니다
// 예 : CorePoolSize = 3, MaximumPoolsize = 6, LinkedBlockingQueue (10) // RejectedExecutionHandler 기본 처리 방법은 다음과 같습니다. threadpoolexecutor.abortpolicy // ThreadPoolexecutorervice = new ThreadPooleExecutor (Corepoolsize, maximumpoolsize, 1L, Seeconds, Seconds, LinkedBlockingqueue <Runnable> (10)); // 1. 스레드 풀에서 실행되는 스레드 (즉, ExecutorService.execute 호출)가 LinkedBlockingqueue.init (10)에 도달하지 않으면 현재 실행 된 스레드 수는 다음과 같습니다. Corepoolsize (3) // 2. 스레드 수가 링크드 블로킹 Queue.init (10)을 초과하고> = init (10)+corepoolsize (3)를 초과하고 init (10)+maximumpoolsize보다 작습니다. 현재 시작된 스레드의 수는 다음과 같습니다. (현재 스레드 Init (10)) // 3. 호출되는 스레드 수가 init (10)+maximumpoolsize를 초과하는 경우 거부 executionHandler의 규칙에 따라 처리됩니다.
정보 : 거부 executionAndler의 여러 기본 구현에 대한 설명
// 기본값이 사용됩니다 : ThreadPoolexecutor.abortPolicy. 핸들러가 거부되고 런타임 거부 집행률을 던집니다. RejectedExecutionHandler Policy = New ThreadPoolexecutor.abortPolicy (); //// threadPoolexecutor.callerRunspolicy에서 스레드는 실행 자체를 호출하여 작업을 실행합니다. 이 전략은 새로운 작업 제출 속도를 늦출 수있는 간단한 피드백 제어 메커니즘을 제공합니다. // policy = new ThreadPoolexecutor.callerRunspolicy (); //// threadpoolexecutor.discardPolicy에서 실행할 수없는 작업이 삭제됩니다. // policy = new ThreadPoolexecutor.DiscArdPolicy (); /// in ThreadPoolexecutor.discardOldestPolicy, 실행자가 닫히지 않으면 작업 대기열의 헤드의 작업이 삭제되고 프로그램의 실행이 다시 시작됩니다 (이 과정이 다시 실패하면 반복). // policy = new ThreadPoolexecutor.discardOldestPolicy ();
Java 스레드 풀의 구현 방법과 차이점에 대한 위의 소개는 내가 공유 한 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.