Multithreading concurrency is often cumbersome, and if you use the spring container to manage business beans, it's a lot easier. Spring encapsulates the implementation of multithreaded implementations of Java, and you only need to focus on the processes of concurrency and some of the concurrency load, specifically how to use spring to handle concurrent transactions:
1. Understanding the Taskexecutor interface
Spring's Taskexecutor interface is equivalent to the Java.util.concurrent.Executor interface . In fact, the main reason it exists is to abstract the dependency on Java 5 when using the thread pool. This interface has only one method, execute (Runnable Task), which accepts an execution task based on the semantics and configuration of the thread pool. The Taskexecutor was originally created to provide an abstraction of a thread pool to other spring components when needed. For example, the Applicationeventmulticaster component, the JMS Abstractmessagelistenercontainer, and the integration of quartz use Taskexecutor abstraction to provide a thread pool. Of course, if your bean needs thread pool behavior, you can use this abstraction layer as well.
2. Implementation class for the Taskexecutor interface
(1) Simpleasynctaskexecutor class
This implementation does not reuse any threads, or it starts a new thread each time it is called. However, it also supports limiting the number of concurrent totals, blocking new calls until a location is freed when the total number of threads concurrently limits is exceeded. If you need a real pool, please keep looking down.
(2) Synctaskexecutor class
This implementation does not execute asynchronously. Instead, each call is executed in the thread that initiated the call. Its main use is when there is no need for multi-threading, such as a simple test case.
(3) Concurrenttaskexecutor class
This implementation is the wrapper for the Java 5 Java.util.concurrent.Executor class. There is another alternative, the Threadpooltaskexecutor class, which exposes the configuration parameters of executor as bean properties. It is seldom necessary to use concurrenttaskexecutor, but if the threadpooltaskexecutor is not sufficient, Concurrenttaskexecutor is another alternative.
(4) Simplethreadpooltaskexecutor class
This implementation is actually a subclass of the Quartz Simplethreadpool class that listens for spring's lifecycle callbacks. This is typical use when you have a thread pool that needs to be quartz and non-quartz components.
(5) Threadpooltaskexecutor class
It does not support any substitution or downstream migration of the java.util.concurrent package. Both Doug Lea and Dawid Kurzyniec implemented different package structures for Java.util.concurrent implementations, which prevented them from running correctly. This implementation can only be used in a Java 5 environment, but it is the most commonly used in this environment. Its exposed bean properties can be used to configure a java.util.concurrent.ThreadPoolExecutor to wrap it in a taskexecutor. If you need more advanced classes, such as Scheduledthreadpoolexecutor, we recommend that you use Concurrenttaskexecutor instead.
(6) Timertaskexecutor class
This implementation uses a timertask as the implementation behind it. It differs from synctaskexecutor in that the method invocation is performed in a separate thread, although it is synchronous in that thread.
(7) Workmanagertaskexecutor class
This implementation uses the COMMONJ Workmanager as its underlying implementation and is the most important class for configuring COMMONJ Workmanager applications in spring context. Similar to Simplethreadpooltaskexecutor, this class implements the Workmanager interface, so it can be used directly as a workmanager.
3. Simple Hellword
3.1 Thread Classes
Public classMessageprintertaskImplementsRunnable {PrivateString message; PublicMessageprintertask () {} Publicmessageprintertask (String message) { This. Message =message; } Public voidrun () {Try{Thread.Sleep (5000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (message); }}
3.1 Thread management tool classes
ImportOrg.springframework.core.task.TaskExecutor; Public classTaskexecutorutil {PrivateTaskexecutor Taskexecutor; Publictaskexecutor Gettaskexecutor () {returnTaskexecutor; } Public voidsettaskexecutor (Taskexecutor taskexecutor) { This. Taskexecutor =Taskexecutor; } Public voidPrintmessages (Runnable R,inti) {Taskexecutor.execute (R); System.out.println ("Add Thread:" +i); }}
Applicationcontext.xml
<?XML version= "1.0" encoding= "UTF-8"?> <Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/c Ontext/spring-context-3.0.xsd "> <!--Asynchronous thread pool - <BeanID= "Taskexecutor"class= "Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!--number of core threads - <property name= "Corepoolsize" value= "2"/> <!--Maximum number of threads - < Propertyname= "Maxpoolsize"value= "3" /> <!--Maximum Queue Length >=mainexecutor.maxsize - < Propertyname= "Queuecapacity"value= "Ten" /> <!--the thread pool maintains idle time allowed by threads - < Propertyname= "Keepaliveseconds"value= "+" /> <!--processing policy for the thread pool to reject tasks (wireless threads available) - <!--If this is not done, when the thread is full and the queue is full, continue to increase the task, throw an exception, reject the task - < Propertyname= "Rejectedexecutionhandler"> <Beanclass= "Java.util.concurrent.threadpoolexecutor$callerrunspolicy" /> </ Property></Bean> <BeanID= "Taskexecutorutil"class= "Taskexecutorutil"> <!--<constructor-arg ref= "Taskexecutor"/> - < Propertyname= "Taskexecutor"ref= "Taskexecutor" /> </Bean> <!--Managed Threads -<BeanID= "Messageprintertask"class= "Messageprintertask"> </Bean> </Beans>
Test
ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;/*** Hello world! **/ Public classApp { Public Static voidMain (string[] args) {ApplicationContext appContext=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Taskexecutorutil te= (taskexecutorutil) appcontext.getbean ("Taskexecutorutil"); for(inti = 0; I < 25; i++) {Messageprintertask m=NewMessageprintertask ("Message" +i); Te.printmessages (M,i); } System.out.println ("11111111111111111111111"); }}
Result output
Add thread:0Add Thread:1Add Thread:2Add Thread:3Add Thread:4Add Thread:5Add Thread:6Add Thread:7Add Thread:8Add Thread:9Add Thread:10Add Thread:11Add Thread:12message1message0message13add Thread:13message12add Thread:14Add Thread:15Add Thread:16message2message4message17add Thread:17message3add Thread:18Add Thread:19Add Thread:20message5message7message21add Thread:21stmessage6add Thread:22Add Thread:23Add Thread:2411111111111111111111111Message9message8message10message14message15message11message18message19message16message22message23message20message24
Explain:
1. Because the thread class sleeps for 5 seconds, the add thread adds 13 threads (3 maximum threads + 10 waits in the queue) 5 seconds ago, so it does not throw an exception due to the policy being full (rejectedexecutionhandler). ,
Other threads waiting to join the queue
2. After five seconds to print, then continue to addthread, print the message, note that the current maximum thread execution is 3, the rest is waiting in the queue, and then the remaining threads are printed, and 111111111111 is the main thread
4. Thread class is java.util.concurrent.ThreadPoolExecutor:
The thread pool class is java.util.concurrent.ThreadPoolExecutor and is commonly constructed by: Threadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit,blockingqueue<Runnable> Workqueue,rejectedexecutionhandler handler) Corepoolsize: The thread pool maintains a minimum number of threads maximumpoolsize: The maximum number of threads maintained by the thread pool KeepAliveTime: The thread pool maintains the idle time allowed by threads Unit: the unit that the thread pool maintains the idle time allowed by threads Workqueue: The buffer queue used by the wire pool handler: The thread pool's processing policy for rejected tasks a task by execute (Runnable) Method is added to the thread pool, the task is an object of type runnable, and the execution method of the task is the run () method of the Runnable type object. When a task is added to the thread pool through the Execute (Runnable) method: If the number of thread pools at this time is less than corepoolsize, even if the threads in the thread pool are idle, a new thread is created to handle the task being added. 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. 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. 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. When the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for more than KeepAliveTime, the thread is terminated. This allows the thread pool to dynamically adjust the number of threads in the pool. The unit optional parameters are several static properties in Java.util.concurrent.TimeUnit: nanoseconds, microseconds, MILLISECONDS, SECONDS. Workqueue I often use: Java.util.concurrent.ArrayBlockingQueuehandler has four options: Threadpoolexecutor.abortpolicy () Throw Java.util.concurrent.ReJectedexecutionexception exception Threadpoolexecutor.callerrunspolicy () retries to add the current task, he will automatically repeat the call to execute () Method Threadpoolexecutor.discardoldestpolicy () Discard the old task Threadpoolexecutor.discardpolicy () discard the current task
spring-thread pool (1)