이 예제는 참조를 위해 Java 필기 스레드 풀의 구현 코드를 공유합니다. 특정 내용은 다음과 같습니다
1. 스레드 풀은 멀티 스레딩의 한 형태입니다. 처리 중에 작업이 큐에 추가 된 다음 스레드가 작성된 후에 이러한 작업이 자동으로 시작됩니다. 스레드 풀 스레드는 모두 배경 스레드입니다.
2. 간단한 스레드 풀 아키텍처
3. 간단한 스레드 풀 코드 (자체 최적화)
import java.util.list;/** * 스레드 인터페이스 * * @author yjian * @date 14:49 2017/10/14 **/public interface ithreadpool {// 작업 추가 void execute (runnable task); // 작업 추가 void execute (runnable [] 작업); // 작업 void execute (list <runnable> 작업)를 추가합니다. // 스레드 void void destroy ();} import java.util.linkedlist; import java.util.list; import java.util.concurrent.atomic.atomiclong;/** * 스레드 구현 클래스 (간단한 구현, 자체 최적화. 아이디어 제공) * * @@author yjian * @date 14:49 2017/10/14 **/ @represswarnings ( ") ithreadpool {// 스레드 수는 기본적으로 static int worker_number = 5; // 완성 된 스레드 수는 정적 휘발성 int sumcount = 0입니다. // 작업 대기열 목록은 스레드-안전하지 않으며 정적 목록을 차단하기 위해 최적화 할 수 있습니다. // Thread WorkGroup WorkerThread [] workthreads; // Atomic static atomiclong streadnum = new atomiclong (); 정적 ThreadPoolimpl ThreadPool; // 구성 방법 public ThreadPoolimpl () {this (worker_number); } public ThreadPoolImpl (int Workernum) {this.worker_number = 직장; // 작업자 실 // (int i = 0; i <worker_number; i ++) {workthreads [i] = new workerthread (); 스레드 스레드 = 새 스레드 (Workthreads [i], "ThreadPool-Worker" + ThreadNum.incrementAndget ()); system.out.println ( "스레드 수 초기화" + (i + 1) + "-------------------------------------- getname ()); thread.start (); }} @override public String toString () {return "return"작업자 스레드 수는 " + worker_number +"완료된 작업 번호 " + sumCount +"대기 작업 번호 " + taskqueue.size (); } // 스레드 풀 가져 오기 공개 정적 정적 iThreadpool getThreadPool () {return getThreadPool (worker_number); } public static ithreadpool getThreadpool (int workernum) {// 결함 공차, 0 이하이면 0 이하이면 스레드의 기본 수는 if (workernum <= 0) {workernum = worker_number; } if (ThreadPool == NULL) {ThreadPool = New ThreadPoolimpl (Workernum); } return strandpool; } @override public void execute (runnable task) {synchronized (taskqueue) {taskqueue.add (task); taskqueue.notifyall (); }} @override public void execute (runnable [] tasks) {synchronized (taskqueue) {for (runnable task : tasks) {taskqueue.add (task); } taskqueue.notifyall (); }} @override public void execute (list <runnable> tasks) {synchronized (taskqueue) {for (runnable task : tasks) {taskqueue.add (task); } taskqueue.notifyall (); }} @override public void destrove () {// 루프에 작업이 여전히 존재하는 곳은 어디에 있습니까? } catch (InterruptedException e) {e.printstacktrace (); }} // 작업 대기열이 처리 된 경우 스레드를 파괴하고 (int i = 0; i <worker_number; i ++) {workthreads [i] .setworkerflag (); Workthreads [i] = null; } threadpool = null; taskqueue.clear (); } // 작업자 스레드 수영장 클래스 CREATE STREED STREED {// 현재 스레드를 식별하는 데 사용하여 사용 가능한 상태 상태에 속합니다. 개인 부울 isrunning = true; @override public void run () {runnable runnable = null; // while (isrunning) {// 비 스레드-세이프, 그래서 동기화되지 않은 (taskqueue) {while (isrunning && taskqueue.isempty ()) {tratk 큐가 비어 있으면 20 밀리 초의 청취 작업이 taskque.wait (20)를 기다리십시오. } catch (예외 e) {e.printstacktrace (); }} // 작업 큐가 비어 있지 않으면 (! taskqueue.isempty ()) {runnable = taskqueue.remove (0); // 첫 번째 task}} if (runnable! = null) {runnable.run (); } sumCount ++; 실행 가능 = null; }} // 스레드 파괴 공개 void setworkerflag () {isrunning = false; }}} import java.util.arraylist; import java.util.list;/** * 테스트 클래스 * * @author yjian * @date 15:37 2017/10/14 **/public class threadpooltest {public static void main (strings [] args) {// get hreadpool t = threadpoolmpl.getthreadpool (20); List <Runnable> taskList = new ArrayList <Runnable> (); for (int i = 0; i <100; i ++) {tasklist.add (new task ()); } // task t.execute (tasklist)를 실행합니다. System.out.println (t); // 스레드 파괴 t.destroy (); System.out.println (t); } 정적 클래스 작업은 실행 가능 {개인 정적 휘발성 int i = 1; @override public void run () {system.out.println ( "현재 처리 된 스레드 :" + 스레드. }}}스프링 소스 코드를 연구 한 후 코드에서 일반적으로 사용되는 스프링을주의 깊게 확인하십시오. 작성 프로그램의 사양은 봄과 동일해야합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.