Java Multithreading and thread pool (GO)

Source: Internet
Author: User

1. Why use a thread pool

 
uses existing objects to serve, which is why pooled resources technology is generated.

Thread pooling is primarily used to address thread life-cycle overhead and resource-poor issues. By reusing threads for multiple tasks, the overhead of thread creation is distributed across multiple tasks, and the delay caused by thread creation is eliminated because the thread already exists when the request arrives. In this way, you can immediately service the request and use the application to respond faster. In addition, the lack of resources can be prevented by adjusting the number of threads in the thread appropriately.

2. Components of the thread pool

A relatively simple thread pool should contain at least the thread pooling manager, worker threads, task queues, task interfaces, and so on. The role of the thread pool manager is to create, destroy, and manage thread pools, put worker threads in the thread pool, the worker thread is a thread that can loop through the task, and wait in the absence of a task; the role of a task queue is to provide a buffer mechanism to place tasks that are not processed in task queues The task interface is the interface that each task must implement, which is used to specify the entry of the task, the finishing work after completion of the task, the execution state of the task, and so on, and the worker thread dispatches the execution of the task through the interface.

The thread pool manager has at least the following capabilities: Create a thread pools, destroy the thread pool, and add new tasks.

A worker thread is a thread that can loop through a task and waits when there is no task.

The task interface is to provide a unified interface for all tasks so that worker threads can handle it. The task interface mainly stipulates the entrance of the task, the finishing work after completion of the task, the execution status of the task, etc.

3. Thread pool suitable for application occasions

When a server accepts requests for a large number of short threads, it is very appropriate to use thread pooling technology, which can greatly reduce the number of threads created and destroyed, and increase the efficiency of the server. However, threads require a long time to run, that is, the thread runs longer than ....

The above information is from the following articles: http://www.blogjava.net/stevenjohn/archive/2011/12/12/366161.html

One, Java comes with thread pool

Let's take a look at Java's own thread pool example and turn on the 5 thread print string list:

 Packagecom.luo.test;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit; Public classThreadTest { Public Static voidMain (string[] args) {List<String> strlist =NewArraylist<string>();  for(inti = 0; I < 100; i++) {Strlist.add ("String" +i); }        intThreadnum = Strlist.size () < 5? Strlist.size (): 5; Threadpoolexecutor Executor=NewThreadpoolexecutor (2, Threadnum, 300, Timeunit.milliseconds,NewArrayblockingqueue<runnable> (3),                NewThreadpoolexecutor.callerrunspolicy ());  for(inti = 0; i < threadnum; i++) {Executor.execute (NewPrintstringthread (i,strlist,threadnum));    } executor.shutdown (); }}classPrintstringthreadImplementsRunnable {Private intnum; PrivateList<string>strlist; Private intThreadnum;  PublicPrintstringthread (intNum, list<string> strlist,intthreadnum) {         This. num =num;  This. strlist =strlist;  This. Threadnum =Threadnum; }     Public voidrun () {intLength = 0;  for(String str:strlist) {if(length% Threadnum = =num) {System.out.println ("Thread Number:" + num + ", string:" +str); } length++; }    }}

Java self-brought thread pool construction method

Threadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepalivetime,timeunit Unit,blockingqueue<Runnable>Workqueuerejectedexecutionhandler handler) Corepoolsize: The thread pool maintains the minimum number of threads, and also the number of core threads, including the idle thread Maximumpoolsize: The thread pool maintains the maximum number of threads KeepAliveTime: The thread pool maintains the idle time allowed by threads unit: The pool maintains the idle time allowed by the thread Workqueue: Buffer queue handler used by the Wire pool: The thread pool's processing strategy for rejecting tasks when a task is added to the thread pool by the Execute (Runnable) method:1, if the number in the thread pool is less than corepoolsize at this point, even if the threads in the thread pool are idle, create a new thread to handle the task being added. 2, if the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is placed in the buffer queue. 3, if the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the task being added. 4, if the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled by handler the policy specified. That is: the priority of the processing task is: Core thread corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to handle the rejected task. 5. When the number of threads in the thread pool is greater than corepoolsize, the thread will be terminated if a thread has more than KeepAliveTime idle time. This allows the thread pool to dynamically adjust the number of threads in the pool.

In fact, the above example code has shortcomings, if you see the shortcomings, it means that you understand the thread pool. Otherwise you can see a few more times oh.

Second, spring thread pool configuration

3.1, calling

directly

New threadpooltaskexecutor ();   // buffer queue  used by the thread pool Pooltaskexecutor.setqueuecapacity ($);   // The thread pool maintains a minimum number  of threads Pooltaskexecutor.setcorepoolsize (5);   // Maximum number  of threads maintained by the thread pool Pooltaskexecutor.setmaxpoolsize (+);   // the thread pool maintains idle time  allowed by threads Pooltaskexecutor.setkeepaliveseconds (30000);  

3.2, through the configuration file

<BeanID= "Pooltaskexecutor"class= "Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">   <!--number of core threads, default = 1 -   < Propertyname= "Corepoolsize"value= "5" />   <!--Maximum number of threads, default = Integer.max_value -   < Propertyname= "Maxpoolsize"value= " the" />   <!--queue maximum length, generally need to set the value >=notifyScheduledMainExecutor.maxNum; default to Integer.max_value -   < Propertyname= "Queuecapacity"value= "$" />   <!--The thread pool maintains the idle time allowed by threads, which defaults to 60s -   < Propertyname= "Keepaliveseconds"value= "+" />   <!--The thread pool's processing strategy for rejecting tasks (which are available on a wireless path) currently only supports AbortPolicy, Callerrunspolicy; -   < Propertyname= "Rejectedexecutionhandler">       <!--AbortPolicy: Throwing java.util.concurrent.RejectedExecutionException Exceptions directly -       <!--callerrunspolicy: The main thread executes the task directly, and then tries to add the next task to the thread pool after execution, which effectively reduces the speed of adding tasks to the thread pool -       <!--discardoldestpolicy: Discard old tasks, temporarily unsupported; causes the discarded task to not be executed again -       <!--Discardpolicy: Discards the current task, temporarily does not support, causes the discarded task to not be executed again -       <Beanclass= "Java.util.concurrent.threadpoolexecutor$callerrunspolicy" />   </ Property></Bean>

Java Multithreading and thread pool (GO)

Related Article

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.