java 多线程处理一个list的集合
Posted 孟令杰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 多线程处理一个list的集合相关的知识,希望对你有一定的参考价值。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class App
public static final String module = App.class.getName();
public static void main(String[] args)
try
List<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++)
list.add(i + ",");
System.out.println(new App().list2Str(list, 5));
catch (Exception e)
e.printStackTrace();
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();
<span id="transmark"></span>
如果您喜欢我写的博文,读后觉得收获很大,不妨小额赞助我一下,让我有动力继续写出高质量的博文,感谢您的赞赏!!!
开发者涨薪指南 48位大咖的思考法则、工作方式、逻辑体系以上是关于java 多线程处理一个list的集合的主要内容,如果未能解决你的问题,请参考以下文章