1. Thread Pool class
Importjava.util.LinkedList;Importjava.util.List; Public classMythreadpool {//the number of default threads in a thread pool is 5 Private Static intWorker_num = 5; //Working Threads Privateworkthread[] workthreads; //Tasks not processed Private Static volatile intFinished_task = 0; //task queue, as a buffer, the list thread is unsafe so it needs to be synchronized during use. PrivateList<runnable> Taskqueue =NewLinkedlist<runnable>(); //single-case mode Private StaticMythreadpool ThreadPool; //Privatization Construction Method PrivateMythreadpool () { This(5); } //to create the thread pool, num is the number of worker threads PrivateMythreadpool (intnum) {Mythreadpool.worker_num=num; Workthreads=NewWorkthread[num]; for(inti = 0; i < num; i++) {Workthreads[i]=NewWorkthread (); Workthreads[i].start (); } } //get a thread pool, default number of threads Public StaticMythreadpool Getthreadpool () {returnGetthreadpool (Mythreadpool.worker_num); } //Singleton mode to get a thread pool Public StaticMythreadpool Getthreadpool (intnum) { if(Num <= 0) {num=Mythreadpool.worker_num; } if(ThreadPool = =NULL){ synchronized(Mythreadpool.class){ if(ThreadPool = =NULL) ThreadPool=Newmythreadpool (num); } } returnThreadPool; } /*** Perform a task * Add the task to the end of the task queue and wait for the worker thread to schedule *@paramTask*/ Public voidExecute (Runnable Task) {synchronized(taskqueue) {taskqueue.add (Task); Taskqueue.notify (); } } /*** Bulk Execution Tasks * Place tasks at the end of the task queue and wait for worker threads to be dispatched *@paramTask*/ Public voidExecute (runnable[] task) {synchronized(taskqueue) { for(Runnable runnable:task) {taskqueue.add (Runnable); } taskqueue.notify (); } } /*** Bulk Execution Tasks * Place tasks at the end of the task queue and wait for worker threads to be dispatched *@paramTask*/ Public voidExecute (list<runnable>Task) { synchronized(taskqueue) { for(Runnable runnable:task) {taskqueue.add (Runnable); } taskqueue.notify (); } } /*** Destroy thread pool * Destroy all threads when all tasks are complete, otherwise wait for task queue tasks to complete before destroying*/ Public voiddestroy () { while(!taskqueue.isempty ()) {//If there's still a job to do, just wait and see. Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } } //worker thread stops working and is set to null for(inti = 0; i < Mythreadpool.worker_num; i++) {workthreads[i].stopworker (); Workthreads[i]=NULL; } ThreadPool=NULL; Taskqueue.clear (); } //returns the number of worker threads Public intGetworkthreadnumber () {returnWorker_num; } //returns the number of completed tasks Public intGetfinishedtasknumber () {returnFinished_task; } //returns the length of the task queue, which is the number of tasks that have not yet been processed Public intGetwaittasknumber () {returntaskqueue.size (); } //override tostring Method, return thread pool information: number of worker threads and number of completed tasks@Override PublicString toString () {return"Workthread Number:" + Worker_num + "finished task number:" + finished_task + "Wait task number:" +Getwaittasknumber (); } /*** Inner class, worker thread used to execute task thread *@authorLiu **/ Private classWorkthreadextendsthread{//whether the worker thread is valid for a natural end of the worker thread Private BooleanIsRunning =true; /** The key point of the worker thread is that if the task queue is not empty, the task execution is removed, and if the task queue is empty, wait. Do not remove execution until task queue has a task*/@Override Public voidrun () {Runnable R=NULL; while(isrunning) {//queue is empty synchronized(taskqueue) { while(IsRunning &&Taskqueue.isempty ()) { Try{taskqueue.wait (20); } Catch(interruptedexception e) {e.printstacktrace (); } } if(!Taskqueue.isempty ()) { //Remove Taskr = Taskqueue.remove (0); } } if(r! =NULL) {r.run (); //complete the task plus aFinished_task + = 1; } R=NULL; } } //stop working and let the thread run through the Run method naturally ends Public voidStopworker () { This. isrunning =false; } }}
2. Test code
Public classTestthreadpool { Public Static voidMain (string[] args) {//Create a thread pool of 5 threadsMythreadpool t = Mythreadpool.getthreadpool (5); Runnable[] R=NewRunnable[] {NewTask (),NewTask (),NewTask ()}; T.execute (R); R=NewRunnable[] {NewTask (),NewTask (),NewTask ()}; T.execute (R); System.out.println (t); T.destroy ();//all threads are executed before DestorySystem.out.println (t); } //Task Class Static classTaskImplementsRunnable {Private Static volatile inti = 1; @Override Public voidRun () {//Perform TasksSYSTEM.OUT.PRINTLN ("task" + (i++) + "Finish"); } }}
3. Running Results
Note: Refer to the online code and ideas, through their own modifications and debugging completed
Implementation of the Java thread pool