Java thread Pool Object Threadpoolexecutor

Source: Internet
Author: User

Threadpoolexecutor Introduction:

The thread pool class provided by Java;

Threadpoolexecutor Effect:

Two functions:

1, used to detach the execution task and the current thread;

2, the main design intention: Re-use thread object;

Threadpoolexecutor using:

  Instantiation:

 Public Threadpoolexecutor (int  corepoolsize,                              int  maximumpoolsize,                              Long  KeepAliveTime,                              timeunit unit,                              blockingqueue<Runnable> workQueue) {          This (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,             executors.defaultthreadfactory (), DefaultHandler);    }

This is one of the construction methods of Threadpoolexecutor, with the least incoming parameters, the following is the parameter description:

  corepoolsize: Sets the thread pool's number of threads; This parameter: when the number of tasks that are added to the thread pools is less than the number of cores, the thread pool prioritizes the creation of new threads rather than reusing previously existing threads (regardless of whether the thread is available or not);

Source Support, Threadpoolexecutor's Execute (Runnable) method has the following source code:

  maximumpoolsize: Set line thread create maximum number of threads; This parameter is used to restrict thread pool creation of unlimited threads;

Source Support, Threadpoolexecutor Addworker (Runnable, Boolean) method has the source code as follows:

 KeepAliveTime: Sets the lifetime of the thread pool to be created;

Source code support, Threadpoolexecutor Gettask () method has the source code as follows; Source code Description: The created thread will get a new task from the task queue and will close the thread if it has not been acquired after KeepAliveTime time;

 

  Unit : sets the time unit at which thread pool threads survive;

  WorkQueue: Sets the queue that the thread pool uses to hold tasks;

Note: The Threadpoolexecutor thread pool creates new threads that depend not only on the corepoolsize variable, but also on the value returned by the offer (E) method of the task queue; For example, to create a cache thread pool, it relies on a special task queue: synchronousqueue<e>;

Source Support, Threadpoolexecutor's Execute (Runnable) method has the following source code:

Example: Creating a fixed thread pool and a cache thread pool;

  fixed thread pool, the corepoolsize and maximumpoolsize settings are the same, in Executors.newfixedthreadpool (10) has the source code example:

     Public Static Executorservice newfixedthreadpool (int  nthreads) {        returnnew  Threadpoolexecutor (Nthreads, nthreads,                                      0L, timeunit.milliseconds,                                      new Linkedblockingqueue<runnable>());    }

  cacahe thread pool, need to pass in a special Blockingqueue object, the object needs to return False in the offer, and be able to hear in the poll method of the task to enter; Java Provides a Synchronousqueue class, which is one such object; in the Executors.newcachedthreadpool () method, there is an example of the source code:

     Public Static Executorservice Newcachedthreadpool () {        returnnew threadpoolexecutor (0, Integer.max_value,                                      60L, timeunit.seconds,                                      new synchronousqueue<runnable >());    }

 Common Methods Tips:

    void Execute (Runnable command): task submission method; The thread pool executes all of the submitted methods in sequence;

    void Shutdown (): stops subsequent task commits, but executes all tasks in the current thread pool, and the method works: The thread pool interrupts all currently idle threads, but does not guarantee an interruption (see the Interrupt method for thread) The thread in the work will continue to work until it is finished;

Source:

     Public void shutdown () {        finalthis. Mainlock;        Mainlock.lock ();         Try {            checkshutdownaccess ();            Advancerunstate (SHUTDOWN);            Interruptidleworkers ();//    Interrupts all idle threads             //  hooks for Scheduledthreadpoolexecutor         finally  {            mainlock.unlock ();        }        Tryterminate ();    }

   list<runnable> Shutdownnow (): terminates the thread pool immediately; The function of this method is that the thread pool will break all created threads without saving a certain interrupt; the thread pool removes all remaining tasks from the task queue, does not execute, and saved in a list to be returned to;

Method source code:

 Public List<runnable> Shutdownnow () {        List<Runnable> tasks;         Final  This . Mainlock;        Mainlock.lock ();         Try {            checkshutdownaccess ();            Advancerunstate (STOP);            Interruptworkers ();             = drainqueue ();         finally {            mainlock.unlock ();        }        Tryterminate ();         return tasks;    }

Threadpoolexecutor task execution Process diagram:

  

Threadpoolexecutor notes on Use note:

Clearly need to use that type of thread pool, when instantiating Threadpoolexecutor, the incoming parameters will be different from the created thread pool, pay particular attention to the incoming blockingqueue parameter, if you need to use the cache thread pool, Please ensure that Blockingqueue's offer method returns false; see Synchronousqueue class;

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.