Multi‑thread multipart traversal set list (spring thread pool), listspring
Spring-based ThreadPoolTaskExecutor thread pool multipart traversal to read the list of Sets
The Code is as follows:
1. Define the thread pool
<Bean id = "threadPoolTaskExecutor" class = "org. springframework. scheduling. concurrent. ThreadPoolTaskExecutor"> <! -- Initial thread pool size --> <property name = "corePoolSize" value = "10"/> <! -- Maximum thread pool size --> <property name = "maxPoolSize" value = "30"/> </bean>
2. Main thread code
@ Autowired public ThreadPoolTaskExecutor threadPoolTaskExecutor; private void doReadList () throws InterruptedException, ExecutionException {/** initialization set **/List <String> list = new ArrayList <String> (); for (int I = 0; I <100; I ++) {list. add ("test --" + I );} /** receive the returned results of each segment of the Set **/List <Future <Boolean> futureList = new ArrayList <Future <Boolean> (); /** Total number of items in the Set **/int size = list. size ();/** number of segments split into sets **/int sunSum = 1 0; int listStart, listEnd;/*** when the total number of items is less than 10, use the total number of items as the thread cut score **/if (sunSum> size) {sunSum = size ;} /** define sub-thread **/SunCallable sunCallable;/** split the list into 10 multi-thread executions **/for (int I = 0; I <sunSum; I ++) {/*** calculate the start and end of a cut **/listStart = size/sunSum * I; listEnd = size/sunSum * (I + 1 ); /** the last thread may be different from other threads **/if (I = sunSum-1) {listEnd = size ;} /** thread disconnection **/List <String> sunList = list. subList (listStart, ListEnd);/** subthread initialization **/sunCallable = new SunCallable (I, sunList);/*** multi-thread execution ***/futureList. add (taskExecutor. submit (sunCallable);}/** parse the results of each thread segment **/for (Future <Boolean> future: futureList) {if (null! = Future & future. get () {System. err. println ("successful");} else {System. err. println ("failed ");}}}
3 subthread SunCallable code:
Package xxx. xxx. xxx. xx; import java. util. list; import java. util. concurrent. callable; public class SunCallable implements Callable <Boolean> {/** the number of threads currently belonging to **/private int pageIndex; private List <String> list; public SunCallable (int pageIndex, List <String> list) {this. pageIndex = pageIndex; this. list = list;} @ Override public Boolean call () throws Exception {System. err. println (String. format ("pageInd Ex: % s size: % s ", pageIndex, list. size (); Boolean result = Boolean. TRUE; if (null! = List & list. size ()> 0) {for (String str: list) {try {// TODO business processing} catch (Exception e) {result = Boolean. FALSE ;;}} return result ;}}