Introduction to Java Four thread pools, using

Source: Internet
Author: User

Why use a thread pool

1. Reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
2. You can adjust the number of threads in the thread pool to prevent excessive memory consumption based on the system's ability to withstand

Thread pool Process
Threadpoolexecutor Properties: corepoolsize: The size of the core pool, this parameter is very much related to the implementation principle of the thread pool described later. After creating the thread pool, by default, there are no threads in the thread pools, but wait for a task to come before creating a thread to perform the task Maximumpoolsize: thread pool Maximum number of threads KeepAliveTime: Indicates the maximum length of time a thread will be terminated without a task execution. By default, KeepAliveTime only works if the number of threads in the thread pool is greater than corepoolsize, until the number of threads in the thread pool is not greater than Corepoolsizeworkqueue: A blocking queue that stores the tasks waiting to be executed. The choice of this parameter is also important and will have a significant impact on the running process of the thread pool, in general, where the blocking queue has the following options:
Threadfactory: Thread factory, which is used primarily to create threads, Handler: represents the process of handling a policy threadpoolexecutor pool when rejecting a task:1creates a new thread when the pool size is less than corepoolsize and processes the request2when the pool size equals corepoolsize, the request is placed in the workqueue, and the idle thread in the pool is taken from the Workqueue to take the task and handle3when Workqueue does not fit into the new task, the new thread sinks into the pool and processes the request, and if the pool size is propped up to maximumpoolsize, use Rejectedexecutionhandler to do the rejection .4In addition, when the number of threads in the pool is greater than corepoolsize, the extra thread waits for KeepAliveTime for a long time, and if no request can be processed, it will first create the Corepoolsiz thread, and when the thread continues to grow, it is placed in the queue , when both the Corepoolsiz and the Queue are full, a new thread is added and an error is thrown when the thread reaches Maxpoolsize. Org.springframework.core.task.TaskRejectedException
Four thread pools

In fact, four thread pools are threadpoolexecutor, just create different parameters

Newsinglethreadexecutor
Creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.

Newfixedthreadpool
Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.

Newcachedthreadpool
Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread required to process the task, then a partially idle (60 second non-performing task) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.

Newscheduledthreadpool
Create a thread pool of unlimited size. This thread pool supports the need to schedule and periodically perform tasks.

Example (countdownlatch,future)

1, the number of threads is 5, perform 10 tasks, close the thread pool after execution is complete

//use isterminated to determine if a thread is performing Public classTest2 { Public Static voidMain (string[] args) {Executorservice Executorservice= Executors.newfixedthreadpool (5);  for(inti=0;i<10;i++) {Executorservice.execute (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Thread Name" +Thread.CurrentThread (). GetName ()); Thread.Sleep (1000*3); System.out.println ("Thread Name" +thread.currentthread (). GetName () + "End"); } Catch(interruptedexception e) {e.printstacktrace ();        }                }            }); } System.out.println ("Start shutting down the thread pool and no longer accepting new tasks");        Executorservice.shutdown (); System.out.println ("===========");
Wait for all threads to finish executing while(!executorservice.isterminated ()) {} System.out.println ("Thread pool shutdown Complete"); }}
//use Countdownlatch to determine if a thread is performing Public classTest { Public Static voidMain (string[] args) {Executorservice Executorservice= Executors.newfixedthreadpool (5); FinalCountdownlatch Countdownlatch =NewCountdownlatch (10);  for(inti=0;i<10;i++) {Executorservice.execute (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Thread Name" +Thread.CurrentThread (). GetName ()); Thread.Sleep (1000*3); System.out.println ("Thread Name" +thread.currentthread (). GetName () + "End"); } Catch(interruptedexception e) {e.printstacktrace (); }finally {                        //counter minus oneCountdownlatch.countdown ();        }                }            }); }        Try {            //wait for all threads to finish executingcountdownlatch.await (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Start closing thread pool");        Executorservice.shutdown (); System.out.println ("Thread pool shutdown Complete"); }}

//use future to get thread tasks to return results Public classTest { Public Static voidMain (string[] args) {Executorservice Executorservice= Executors.newfixedthreadpool (5);List<Future<String>> futures =NewArraylist<future<string>>();  for(inti=0;i<10;i++){            //Using the future to accept processing resultsfuture<string> future = Executorservice.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {System.out.println ("Thread Name" +Thread.CurrentThread (). GetName ()); returnThread.CurrentThread (). GetName ();            }            });        Futures.add (future); }        Try {             for(future<string>future:futures) {                //The Get method blocks the current thread until the task execution finishes returning the resultSYSTEM.OUT.PRINTLN ("return result =====" +future.get ()); }        } Catch(Exception e) {e.printstacktrace (); }        //start to close the thread poolExecutorservice.shutdown (); System.out.println ("Thread pool shutdown Complete"); }}

Introduction to Java Four thread pools, using

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.