Simple thread pool implementation

Source: Internet
Author: User

The thread pool is like...

A factory receives a business (task) from outside, and it raises a certain number of workers who take the initiative to receive the task and then take charge of the implementation of the task.

However, a good mechanism is needed to manage the business and workers in the factory and manage the assignment of tasks without errors.

 

Return to the thread pool.

There are several basic points as follows: (here we will focus on the simple basics)

1. Use a queue to manage tasks, including the Creation Time, submission time, execution time, and end time. (It is like a project's construction plan or contract plan with similar properties)

2. use a queue to manage the worker threads. The worker threads take the initiative to get the tasks in the thread task queue. If the queue is empty, wait, wait until a task comes in and wake them up!

3. There is a background thread (supervisor) responsible for monitoring the working status of these workers, whether it is idle or busy.

4. The task interface (or abstract class). All executed tasks must comply with the standard. (Just like a company that only makes a list of relevant businesses, ......)

 

The following code is provided, which is also based on the Internet. appropriate adjustments are made and appropriate comments are provided!

 

1. task interface.

Package COM. fox. threadpool; <br/> Import Java. util. date; <br/>/** <br/> * @ author huangfox <br/> * abstract class <br/> * The base class of the task. All tasks must inherit this class. <Br/> * the specific business code of the task is executed in the core () method. <Br/> */<br/> public abstract class task implements runnable {</P> <p> // task creation time <br/> private date createt = NULL; <br/> // submission execution time <br/> private date submitt = NULL; <br/> // execution start time <br/> private date runingt = NULL; <br/> // execution end time <br/> private date finisht = NULL; <br/> // task id <br/> private int taskid; </P> <p> // construct <br/> public task () {<br/> This. createt = new date (); <br/>}</P> <p> @ override <br/> Public void run () {<Br/> core (); <br/>}< br/> // core business code, that is, the main task. <Br/> public abstract void core (); </P> <p> // task details <br/> Public void display () {<br/> system. out. println ("/T task id:" + this. taskid + ";/T creation time:" + this. createt + ";/T submission time:" + this. submitt + ";/t start execution time:" + <br/> This. runingt + ";/T:" + this. finisht); <br/>}</P> <p> Public date getcreatet () {<br/> return createt; <br/>}< br/> Public void setcreatet (date createt) {<br/> This. createt = createt; <br/>}< br/> Public date getsubmitt () {<br/> return submitt; <br/>}< br/> Public void setsubmitt (date submitt) {<br/> This. submitt = submitt; <br/>}< br/> Public date getruningt () {<br/> return runingt; <br/>}< br/> Public void setruningt (date runingt) {<br/> This. runingt = runingt; <br/>}< br/> Public date getfinisht () {<br/> return finisht; <br/>}< br/> Public void setfinisht (date finisht) {<br/> This. finisht = finisht; <br/>}< br/> Public int gettaskid () {<br/> return taskid; <br/>}< br/> Public void settaskid (INT taskid) {<br/> This. taskid = taskid; <br/>}< br/>

 

 

2. Worker -- worker thread

Package com. Fox. threadpool; <br/>/** <br/> * @ author huangfox <br/> * indicates the Thread class used to drive the task. <Br/> * The thread pool is centrally managed. <Br/> */<br/> public class worker extends thread {<br/> // whether the thread can be run <br/> private Boolean isrunning = true; <br/> // waiting for a task (not yet driven). When the task is received and executed, iswating = false. <Br/> private Boolean iswaiting = true; <br/> // thread id <br/> private int id =-1; </P> <p> // construct <br/> public worker (int id) {<br/> This. id = ID; <br/> Start (); <br/>}</P> <p> // stop the current thread <br/> Public void stop () {<br/> This. isrunning = false; <br/>}</P> <p> // obtain the isrunning status <br/> Public Boolean getisrunning () {<br/> return this. isrunning; <br/>}</P> <p> // obtain the iswating status. <br/> Public Boolean getiswaiting () {<br/> return thi S. iswaiting; <br/>}< br/> @ override <br/> Public void run () {<br/> // executes tasks in the task queue cyclically, the premise is that the current thread is runable, that is, isrunning = true <br/> while (isrunning) {<br/> // declare a task <br/> task = NULL; <br/> // extract a task from the task queue <br/> synchronized (threadpool. gettasks () {<br/> // if the task queue is empty, let the task queue wait for a while and check whether a task is executable. <Br/> while (threadpool. istaskemp () {<br/> try {<br/> threadpool. gettasks (). wait (10); <br/>}catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> // when the preceding loop is executed, the task queue is not empty. <br/> // obtain the first task and execute it. <br/> task = threadpool. gettasks (). remove (0); <br/>}< br/> If (task! = NULL) {<br/> // when a task is an executable task (not null), the thread has a task to process, and its status is not idle. <Br/> This. iswaiting = false; <br/> // execute the task <br/> task. run (); <br/>}< br/> // task execution ends <br/> // reset the status of the current thread to idle <br/> This. iswaiting = true; <br/> threadpool. gettasks (). remove (task); <br/> task = NULL; <br/>}// end synchronized <br/>}</P> <p >}< br/>

 

3. threadpool -- Thread Pool

Package COM. fox. threadpool; <br/> Import Java. util. arraylist; <br/> Import Java. util. collections; <br/> Import Java. util. date; <br/> Import Java. util. list; <br/>/** <br/> * @ author huangfox <br/> * thread pool, thread management class <br/> */<br/> public class threadpool {<br/> // thread pool instance <br/> Private Static threadpool pool = threadpool. getinstance (); <br/> // Number of threads in the thread pool <br/> private int max_thread_count = 10; <br/> // thread array <br/> private Static Worker [] workers; <br/> // task queue <br/> Private Static list <task> tasks = collections. synchronizedlist (New arraylist <task> (); <br/> // task id <br/> Private Static int taskid = 0; </P> <p> // <br/> Public static list <task> gettasks () {<br/> return tasks; <br/>}< br/> // Singleton <br/> Public static synchronized threadpool getinstance () {<br/> If (pool = NULL) {<br/> return New threadpool (); <br/>} else {<br/> return Pool; <br/>}</P> <p> // construct <br/> private threadpool () {<br/> This. workers = new worker [max_thread_count]; <br/> for (INT I = 0; I <this. workers. length; I ++) {<br/> This. workers [I] = new worker (I); <br/>}</P> <p> // construct (reload) <br/> // Private threadpool (INT maxthreadcount) {<br/> // This. max_thread_count = maxthreadcount; <br/> // This. workers = new worker [maxthreadcount]; <br/> // For (INT I = 0; I <Maxthreadcount; I ++) {<br/> // This. workers [I] = new worker (I ); <br/>/}< br/> //} </P> <p> // destroy the thread pool <br/> Public synchronized void destory () {<br/> for (INT I = 0; I <this. workers. length; I ++) {<br/> // This is not the stop method of the thread. <Br/> This. workers [I]. stop (); <br/> // clear the thread <br/> This. workers [I] = NULL; <br/>}< br/> // clear the task queue. <Br/> This. tasks. clear (); <br/>}</P> <p> // obtain whether the task queue is empty <br/> Public static Boolean istaskemp () {<br/> return tasks. isempty (); <br/>}</P> <p> // obtain the current thread pool <br/> Public void display () {<br/> system. out. println ("Thread Pool:"); <br/> for (INT I = 0; I <this. workers. length; I ++) {<br/> system. out. println ("/t" + this. workers [I]. GETID () + "/t" + (this. workers [I]. getiswaiting () = true? "Idle": "working ")); <br/>}</P> <p> // Add a single task <br/> Public void addtask (Task newtask) {<br/> synchronized (this. tasks) {<br/> // set the task identifier <br/> newtask. settaskid (++ this. taskid); <br/> // set the task submission time <br/> newtask. setsubmitt (new date (); <br/> // Add the task to the task queue <br/> This. tasks. add (newtask); <br/> // system. out. print ("add task:"); <br/> // newtask. display (); <br/> // wake up the task queue, because if the task queue is empty when the thread retrieves the task, the task is executed. wait (); <br/> // wake up. <Br/> This. Tasks. policyall (); </P> <p >}< br/>}</P> <p>

 

4. Monitor-Monitoring

Package COM. fox. threadpool; <br/>/** <br/> * @ author huangfox <br/> */<br/> public class monitor extends thread {<br/> threadpool pool = NULL; </P> <p> Public Monitor (threadpool p) {<br/> This. pool = P; <br/>}</P> <p> @ override <br/> Public void run () {<br/> while (true) {<br/> pool. display (); <br/> try {<br/> thread. sleep (1000); <br/>} catch (interruptedexception e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}</P> <p >}< br/>

 

5. The following is a test. The specific task tasktest

Package com. Fox. threadpool; </P> <p>/** <br/> * @ author huangfox <br/> * a simple task class. <Br/> */<br/> public class tasktest extends task {<br/> @ override <br/> Public void core () {<br/> system. out. println ("task [" + super. gettaskid () + "] start... "); <br/> try {<br/> // simulate the specific service running time <br/> thread. sleep (2000); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> system. out. println ("task [" + super. gettaskid () + "] ends... "); <br/>}< br/>

 

6. Test the main program

Package COM. fox. threadpool; <br/> public class mainapp {<br/>/** <br/> * @ Param ARGs <br/> */<br/> Public static void main (string [] ARGs) {<br/> threadpool pool = threadpool. getinstance (); <br/> // <br/> monitor m = new monitor (pool); <br/> M. setdaemon (true); <br/> M. start (); <br/> for (INT I = 0; I <10; I ++) {<br/> pool. addtask (New tasktest (); <br/> try {<br/> // controls the speed of adding tasks. <Br/> thread. sleep (150); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/>

 

 

Although it is an entry-level thread pool, the basic principle is clearer.

 

 

 

 

 

 

 

 

 

 

 

 

 

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.