Implementation of the Java thread pool

Source: Internet
Author: User

Composition of the thread pool implementation

A relatively simple thread pool should include at least

Thread pool Manager: Creates, destroys, and manages the thread pool, putting the worker threads into the threads pools;

Worker thread: A thread that can loop through a task and wait while there is no task;

Task queue: Provides a buffering mechanism to place tasks that are not processed in the task queue;

Task interface: the interface that each task must implement, it is mainly used to stipulate the entrance of the task, the finishing work after the task executes, the execution state of the task, etc. The worker thread dispatches the execution of the task through the interface.

Principle

Similar to the buffer in the operating system, the process is as follows:

Start a number of threads and let them wait, and when the client has a new request, it wakes up a waiting thread in the thread pool, letting him handle the client's request, and continues to wait when the process is finished.

Code implementation

   

 Packagethread;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.util.*; Public classThreadPool {Static classthreadpoolmanager{Private intMaxthread; PrivateVector Threadqueue;  Public voidSetmaxthread (intcount) {                 This. Maxthread=count; }                         PublicThreadpoolmanager (intcount)                {Setmaxthread (count); System.out.println ("Starting Thread Pool"); Threadqueue=NewVector ();  for(inti=0;i<=maxthread;i++) {Simplethread thread=NewSimplethread (i);                    Threadqueue.addelement (thread);                Thread.Start (); }            }                         Public voidprocess (String argument) {inti;  for(I=0;i<threadqueue.size (); i++) {Simplethread current=(Simplethread) threadqueue.elementat (i); if(!current.isrunning ()) {System.out.println ("Thread" + (i+1) + "is processing:" +argument);                        Current.setargument (argument); Current.setrunning (true); return; }                }                                if(i==threadqueue.size ()) {System.out.println ("Pool is full,try in Anthor time"); }            }                }            Static classSimplethreadextendsthread{Private BooleanRunningflag; PrivateString argument;  Public Booleanisrunning () {returnRunningflag; }                 Public synchronized voidsetrunning (Boolean Flag) {Runningflag=Flag; if(Flag) { This. Notify (); }        }                 PublicString getargument () {return  This. Argument; }                 Public voidsetargument (String string) {argument=string; }                 PublicSimplethread (intthreadnumber) {Runningflag=false; System.out.println ("Thread" +threadnumber+ "started."); }                 Public synchronized voidrun () {Try {                 while(true){                    if(!Runningflag) {                         This. Wait (); }                    Else{System.out.println ("Process" +getargument () + "... done!"); Sleep (5000); System.out.println ("Thread is sleeping."); Setrunning (false); }                }            } Catch(Exception e) {//Todo:handle ExceptionSystem.out.println ("Interrupt"); }        }    }         Public Static voidMain (string[] args) {Try{BufferedReader Brbufferedreader=NewBufferedReader (NewInputStreamReader (system.in));            string string; Threadpoolmanager Manager=NewThreadpoolmanager (10);  while((String=brbufferedreader.readline ())! =NULL) {manager.process (string); }        } Catch(Exception e) {//Todo:handle Exception        }    }        }

   

   

Implementation of the Java thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.