Java Create thread pool

Source: Internet
Author: User
Tags count thread thread class

The role of the thread pool:

The thread pool function is to limit the number of threads executing in the system.

According to the environment of the system, can automatically or manually set the number of threads to achieve the best effect of the operation, less waste of system resources, many caused the system congestion efficiency is not high. The thread pool controls the number of threads, and other threads wait in line. A task completes, and the first task from the queue is executed. If there is no waiting process in the queue, this resource in the thread pool is waiting. When a new task needs to be run, it can start running if there is a waiting worker thread in the thread pool, otherwise enter the wait queue.

Why do I use a thread pool:

Reduces the number of times to create and destroy threads, and each worker thread can be reused to perform multiple tasks

Depending on the system's affordability, the number of thread threads in the thread pool can be adjusted to prevent the server from exhausting because of excessive memory consumption (each thread requires approximately 1MB of RAM, the more threads open, the greater the memory consumed, and the last crash)

Thread Pool Class

Import java.util.LinkedList; /** * @project Locationgateway * @author sunnylocus * @verson 1.0.0 * @date Aug 2, 2008 * @jdk 1.4.  2 */public class ThreadPool extends Threadgroup {private Boolean isclosed = false;      Whether the thread pool closes private linkedlist workqueue;  Work queue private static int threadpoolid = 1; The thread pool ID public ThreadPool (int poolsize) {//poolsize represents the number of worker threads in the thread pool super (Threadpoolid + ""      );               Specifies the name of the Threadgroup Setdaemon (true);  Inherits to the method that sets whether the daemon thread pool Workqueue = new LinkedList ();   Create a work queue for (int i = 0; i < poolsize i++) {new Workthread (i). Start (); Create and start worker threads, number of thread pools to create how many worker threads}/** adds a new task to the work queue, which is performed by the worker thread */public s    
        ynchronized void Execute (Runnable task) {if (isclosed) {throw new illegalstateexception (); } if (tAsk!= null) {Workqueue.add (Task);//Add a task to the queue notify (); Wake up a worker thread in the Gettask () method}/** remove a task from the work queue and the worker thread will call this method/private SYNCHR    
            onized Runnable gettask (int threadid) throws Interruptedexception {while (workqueue.size () = 0) {    
            if (isclosed) return null;    
            SYSTEM.OUT.PRINTLN ("Worker thread" +threadid+ "Wait for Task ...");             Wait ();    
        If there are no tasks in the work queue, wait for the task} System.out.println ("Worker thread" +threadid+ "Start the task ..."); Return (Runnable) Workqueue.removefirst (); Back to the first element in the queue and remove it from the queue/** close thread pool/public synchronized void Closepool () {if (! isclosed)        {waitfinish ();    
            Wait for worker thread to finish isclosed = true;  Workqueue.clear ();        Clear the Work queue interrupt ();    
           All worker threads in the thread pool, this method inherits from the Threadgroup class}} 
    /** waits for the worker thread to finish all tasks */public void Waitfinish () {synchronized () {isclosed = tr    
            Ue            Notifyall (); Wake up all worker threads that are still waiting for the task in the Gettask () method} thread[] threads = new Thread[activecount ()];    
        Activecount () returns the estimated value of the active thread in the thread group. int count = enumerate (threads);    
            The enumerate () method inherits from the Threadgroup class, obtains all currently active worker threads for (int i =0; i < count; i++) {//For all worker threads in the thread group based on the estimated value of the active thread.  try {threads[i].join ();    
            Wait for worker thread to end}catch (Interruptedexception ex) {ex.printstacktrace ();
    }}/** * Inner class, worker thread, responsible for removing the task from the work queue and executing * @author sunnylocus * *    
        Private class Workthread extends Thread {private int id;    
            The public workthread (int id) {//Parent class constructor method joins the thread to super (threadpool.this,id+ "") in the current ThreadPool thread group; This.id =id;  

  
                The public void run () {while (! isinterrupted ()) {//isinterrupted () method inherits from the thread class to determine whether the thread is interrupted    
                Runnable task = null;     try {task = Gettask (ID);    
                Remove Task}catch (Interruptedexception ex) {ex.printstacktrace ();    
                        
                If Gettask () returns null or if the thread is interrupted while executing gettask (), end this thread if (task = null) return;  try {task.run ();    
                Run Task}catch (Throwable t) {t.printstacktrace (); }//End While}//end run}//end Workthread}

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.