The principle and implementation of Java thread pool learning (I.)

Source: Internet
Author: User

thread pool:
Multithreading technology mainly solves the problem of multiple threads in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput capacity of the processor unit.

Suppose a server takes a task to complete: T1 creates a thread time, T2 the time to execute a task in the thread, T3 destroys the threading time.

if: T1 + T3 is much larger than T2, you can use a thread pool to improve server performance.
A thread pool consists of the following four basic components:
1. Thread pool Manager (ThreadPool): Used to create and manage thread pools, including creating a thread pool, destroying the thread pool, adding new tasks;
2, worker thread (poolworker): Thread pool threads, in the absence of a task in the waiting state, you can cycle the execution of tasks;
3, Task interface (tasks): Each task must be implemented by the interface for the task of scheduling the execution of tasks, it mainly specifies the entry of the task, the completion of the task after the end of the task, the implementation of the mission status, etc.;
4. Task Queue (Taskqueue): Used to store tasks that are not processed. Provides a buffering mechanism.

Thread pooling technology is a technique that focuses on how to shorten or adjust t1,t3 time to improve the performance of server programs. It t1,t3 the start and end of the server program, or some idle time period, so that there is no t1,t3 overhead when the server program processes the client request.

The thread pool not only adjusts the time period generated by the T1,T3, but it also significantly reduces the number of threads created, looking at an example:

Suppose a server handles 50,000 requests a day, and each request requires a separate thread to complete. The number of threads in a thread pool is generally fixed, so the total number of threads does not exceed the number of threads in the thread pool, and the total number of threads is 50000 if the server does not use the thread pool to process these requests. The general thread pool size is far less than 50000. Therefore, server programs that utilize the thread pool do not waste time processing requests in order to create 50000, thereby increasing efficiency.

/** * @ Author WHS * @ Creation Date February 5, 2015 * @ Version V 1.0 */package Thread.pool1;import java.util.collections;import java.util.date;impo RT java.util.linkedlist;import Java.util.list;import org.apache.log4j.logger;/** * thread pool * Create thread pool, destroy thread pool, add new task */public    Final class ThreadPool {private static Logger Logger = Logger.getlogger (ThreadPool.class.getName ());    private static Logger Tasklogger = Logger.getlogger ("Tasklogger");    private static Boolean debug = Tasklogger.isdebugenabled ();    private static Boolean debug = Tasklogger.isinfoenabled ();    /* Singleton, a hungry man type */private static ThreadPool instance = new ThreadPool ();    public static final int system_busy_task_count = 150;    /* Number of threads in the default pool */public static int worker_num = 5;    /* Number of tasks already processed */private static int taskcounter = 0;        public static Boolean systemisbusy = false;    private static List<task> Taskqueue = Collections.synchronizedlist (New linkedlist<task> ());    /* All threads in Pool */public poolworker[] workers; Default configurationConstructor initializes the number of thread pools 5 private ThreadPool () {workers = new poolworker[5];        for (int i = 0; i < workers.length; i++) {workers[i] = new Poolworker (i); }}//Parameter constructor initializes the number of thread pool parameters pool_worker_num private ThreadPool (int pool_worker_num) {worker_num = Pool_w        Orker_num;        Workers = new Poolworker[worker_num];        for (int i = 0; i < workers.length; i++) {workers[i] = new Poolworker (i);    }} public static synchronized ThreadPool getinstance () {return instance; }/** * Add a new task * each additional task will wake up the task queue * @param newtask */public void AddTask (task NewTask) {sy            Nchronized (taskqueue) {newtask.settaskid (++taskcounter);            Newtask.setsubmittime (New Date ());            Taskqueue.add (NewTask);        /* Wake up queue, start execution */Taskqueue.notifyall ();    } logger.info ("Submit task<" + newtask.gettaskid () + ";:" + newtask.info ()); }    /**    * Bulk Add New task * @param taskes */public void Batchaddtask (task[] taskes) {if (Taskes = = NULL | | taskes.        Length = = 0) {return; } synchronized (Taskqueue) {for (int i = 0; i < taskes.length; i++) {if (taskes[i] =                = null) {continue;                } taskes[i].settaskid (++taskcounter);                Taskes[i].setsubmittime (New Date ());            Taskqueue.add (Taskes[i]);        }/* Wake-up queue, start execution */Taskqueue.notifyall ();            } for (int i = 0; i < taskes.length; i++) {if (taskes[i] = = null) {continue;        } logger.info ("Submit task<" + taskes[i].gettaskid () + ";:" + taskes[i].info ());        }}/** * thread pool information * @return */public String GetInfo () {stringbuffer sb = new StringBuffer ();        Sb.append ("\ntask Queue Size:" + taskqueue.size ()); for (int i = 0; i < workers.length; i++) {sb.append ("\nworker" + i + "is" + ((workers[i].iswaiting ())? "        Waiting. ":" Running. "));    } return sb.tostring ();            }/** * Destroy thread pool */public synchronized void Destroy () {for (int i = 0; i < Worker_num; i++) {            Workers[i].stopworker ();        Workers[i] = null;    } taskqueue.clear ();         /** * Pool worker thread */private class Poolworker extends thread {private int index =-1;         /* Whether the worker thread is valid */private Boolean isrunning = true;         /* Whether the worker thread can perform a new task */private Boolean iswaiting = true;             public poolworker (int index) {this.index = index;         Start ();         } public void Stopworker () {this.isrunning = false;         } public boolean iswaiting () {return this.iswaiting; }/** * Cyclic execution of tasks * This may be the key to the thread pool * * * public void RUN () {while (isrunning) {Task r = null;                             Synchronized (Taskqueue) {while (Taskqueue.isempty ()) {try {                         /* Task queue is empty, wait for new tasks to join and wake up */taskqueue.wait (20);                         } catch (Interruptedexception IE) {logger.error (IE);                 }}/* Remove task Execution */R = (Task) taskqueue.remove (0);                     } if (r! = null) {iswaiting = false;                             try {if (debug) {r.setbeginexceutetime (New Date ()); Tasklogger.debug ("worker<" + Index + "> Start execute task<" + R                             . GetTaskID () + ">");                       if (R.getbeginexceutetime (). GetTime ()              -R.getsubmittime (). GetTime () > Tasklogger.debug ("Longer waiting ti Me.                                         "+ r.info () +",< "+ Index +" >,time: "                          + (R.getfinishtime (). GetTime ()-R. Getbeginexceutetime (). GetTime ());  }/* Whether the task needs to be executed immediately */if (r.needexecuteimmediate ())                         {New Thread (R). Start ();                         } else {r.run ();                             } if (Debug) {r.setfinishtime (New Date ()); Tasklogger.debug ("worker<" + Index + "> Finish task<" + r.gettaskid () + "&                             gt; "); if (R.getfinishtime (). GetTime ()-R.getbeginexCeutetime (). GetTime () > () tasklogger.debug ("Longer execution time." + r.info () + ",<" + Index + ">,time:" + (R.getfin                         Ishtime (). GetTime ()-R. Getbeginexceutetime (). GetTime ());                         }} catch (Exception e) {e.printstacktrace ();                     Logger.error (e);                     } iswaiting = true;                 R = null; }             }         }     } }

 

/** * @ Author WHS * @ Creation Date February 5, 2015 * @ Version V 1.0 */package thread.pool1;/* * All Task interfaces * Other tasks must inherit the visit class */import Java.util.date;public    Abstract class Task implements Runnable {//private static Logger Logger = Logger.getlogger (Task.class);    /* Generate time */private Date generatetime = null;    /* Submit Execution Time */private Date submittime = null;    /* Start Execution time */private Date beginexceutetime = null;    /* Execution Finish time */private Date finishtime = null;    Private long taskId;    Public Task () {this.generatetime = new Date ();        }/** * Task execution Entry */@Override public void Run () {System.out.println ("--------------------");        /** * Related Execution code * BeginTransaction ();        * New tasks may arise during execution subtask = Taskcore ();        * CommitTransaction ();        * Add newly generated task Threadpool.getinstance (). Batchaddtask (Taskcore ()); */}/** * All tasks at the core so special business logic execution * @throws Exception */public abstract task[] Taskcore () throws Excepti    On /** * Whether to use database * @return */Protected abstract Boolean usedb ();    /** * is required to execute immediately * @return */protected abstract Boolean needexecuteimmediate ();    /** * Task Information * @return String */public abstract string info ();    Public Date Getgeneratetime () {return generatetime;    Public Date Getbeginexceutetime () {return beginexceutetime;    } public void Setbeginexceutetime (Date beginexceutetime) {this.beginexceutetime = Beginexceutetime;    Public Date Getfinishtime () {return finishtime;    } public void Setfinishtime (Date finishtime) {this.finishtime = Finishtime;    Public Date Getsubmittime () {return submittime;    } public void Setsubmittime (Date submittime) {this.submittime = Submittime;    } public Long GetTaskID () {return taskId;    } public void Settaskid (long taskId) {this.taskid = TaskId; }}

The principle and implementation of Java thread pool learning (I.)

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.