按照线程数量对List数据切分后构建线程执行业务操作
ThreadUtil
public class ThreadUtil {
public ThreadUtil ( ) {
}
public ThreadUtil ( List < ? > list, ThreadFunction function, int perThreadHandleCount, int maxThreadCount) throws Exception {
int total = list. size ( ) ;
int threadCount = total% perThreadHandleCount== 0 ? total/ perThreadHandleCount: total/ perThreadHandleCount+ 1 ;
threadCount = Math . min ( threadCount, maxThreadCount) ;
perThreadHandleCount = total% threadCount== 0 ? total/ threadCount: total/ threadCount+ 1 ;
ExecutorService execPool = Executors . newFixedThreadPool ( threadCount) ;
List < List < ? > > handleDatas = this . getLists ( perThreadHandleCount, list) ;
for ( List < ? > handleData : handleDatas) {
HttpThread serviceThread = new HttpThread ( handleData, function) ;
execPool. submit ( serviceThread) ;
}
execPool. shutdown ( ) ;
}
static class HttpThread extends Thread {
List < ? > list ;
ThreadFunction function ;
public HttpThread ( List < ? > listHandleData, ThreadFunction function) {
this . list = listHandleData;
this . function = function;
}
public void run ( ) {
try {
function. apply ( list) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
private List < List < ? > > getLists ( int threadHandleCount, List < ? > mList) {
List < List < ? > > mEndList= new ArrayList < > ( ) ;
if ( mList. size ( ) % threadHandleCount!= 0 ) {
for ( int j = 0 ; j < mList. size ( ) / threadHandleCount + 1 ; j++ ) {
if ( ( j * threadHandleCount + threadHandleCount) < mList. size ( ) ) {
mEndList. add ( mList. subList ( j * threadHandleCount, j * threadHandleCount + threadHandleCount) ) ;
} else if ( ( j * threadHandleCount + threadHandleCount) > mList. size ( ) ) {
mEndList. add ( mList. subList ( j * threadHandleCount, mList. size ( ) ) ) ;
} else if ( mList. size ( ) < threadHandleCount) {
mEndList. add ( mList. subList ( 0 , mList. size ( ) ) ) ;
}
}
} else if ( mList. size ( ) % threadHandleCount== 0 ) {
for ( int j = 0 ; j < mList. size ( ) / threadHandleCount; j++ ) {
if ( ( j * threadHandleCount + threadHandleCount) <= mList. size ( ) ) {
mEndList. add ( mList. subList ( j * threadHandleCount, j * threadHandleCount + threadHandleCount) ) ;
} else if ( ( j * threadHandleCount+ threadHandleCount) > mList. size ( ) ) {
mEndList. add ( mList. subList ( j * threadHandleCount, mList. size ( ) ) ) ;
} else if ( mList. size ( ) < threadHandleCount) {
mEndList. add ( mList. subList ( 0 , mList. size ( ) ) ) ;
}
}
}
return mEndList;
}
}
ThreadFunction
public interface ThreadFunction {
void apply ( List < ? > list) throws Exception ;
}
测试方法
public static void main ( String [ ] args) throws Exception {
List < String > list = new ArrayList < > ( ) ;
for ( int i = 0 ; i < 100 ; i++ ) {
list. add ( "测试" + i) ;
}
ThreadUtil threadUtil = new ThreadUtil ( list, new ThreadFunction ( ) {
@Override
public void apply ( List < ? > list) {
for ( Object o : list) {
System . out. println ( o. toString ( ) ) ;
}
}
} , 25 , 10 ) ;
}