多线程代码
作者:互联网
更多请访问 www.itkc8.com
public String list2Str(List<String> list, final int nThreads) throws Exception {
if (list == null || list.isEmpty()) {
return null;
}
StringBuffer ret = new StringBuffer();
int size = list.size();
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List<Future<String>> futures = new ArrayList<Future<String>>(nThreads);
for (int i = 0; i < nThreads; i++) {
final List<String> subList = list.subList(size / nThreads * i, size / nThreads * (i + 1));
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
StringBuffer sb = new StringBuffer();
for (String str : subList) {
sb.append(str);
}
return sb.toString();
}
};
futures.add(executorService.submit(task));
}
for (Future<String> future : futures) {
ret.append(future.get());
}
executorService.shutdown();
return ret.toString();
}
}
标签:nThreads,int,StringBuffer,代码,list,new,多线程,size 来源: https://blog.csdn.net/HUXU981598436/article/details/88785375