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 multithreading in Java, and you only need to focus on the processes of concurrent things and some of the concurrency load. Specifically, how to use spring to handle concurrent transactions:
First write the specific transaction logic, implement the Runnable interface, for example
PackageCom.andy.threadDemo;
Public classThreadtranscodeImplementsrunnable{
@Override
Public voidRun () {
System.out.println ("Execute Transaction");
}
All you have to do is configure the thread pool task executor provided by the spring container itself:<Bean ID= "Taskexecutor"
class= "Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
< Propertyname= "Corepoolsize"value= "3" />
< Propertyname= "Keepaliveseconds"value= "$"/>
< Propertyname= "Maxpoolsize"value= "5" />
< Propertyname= "Queuecapacity"value= "+" />
</Bean>Configuration that focuses on four properties during configurationthe next thing to do is to use the thread pool task executor in the business bean of the application itself to perform concurrent transactions. inject a thread pool task executor into the corresponding business bean, just like a normal spring bean. <BeanID= "Bizmanager"
class= "Com.andy. Threaddemo.bizmanager">
< Property name = "taskexecutor" >
< ref Bean = "taskexecutor" />
</ Property >
</Bean>In business code, multiple transactions are typically executed as a for loop for (int k = 0; k < n; k++) {
Taskexecutor.execute (new Threadtranscode ());
}other tedious thread-management tasks are given to the executor to manage. There are two things worth noting .1, Taskexecutor.execute (new Threadtranscode ()); The thread that activates is the daemon thread, the main thread ends, and the daemon will abandon execution, which is logical in the business Chinese, in order to see the execution effect in the unit test, it is necessary to block the main thread by itself. 2, Taskexecutor.execute (new Threadtranscode ()); Execution is not completely secure, and it is possible to throw a run-time exception when the required thread has checked the capacity of the thread queue and, if necessary, capture it.
Using Spring's multithreading mechanism