Java 多线程的一个小例子,保存结果到StringBuffer:
/**
*
* @date: Apr 21, 2021 5:16:38 PM
* @author Henry Li
* @throws ExecutionException
* @throws InterruptedException
*/
@Test
public void testMutilpeThread() throws InterruptedException, ExecutionException {
String[] array = {"410038541200161302015","310038541200161302025","110038541200161302045","910038541200161302055","510038541200161303015","410038541200161303025","210038541200161303045","910038541200161303065","610038541200161304015","510038541200161304025","410038541200161304035","310038541200161304045","210038541200161304055","110038541200161304065","710038541200161305015","610038541200161305025","510038541200161305035","410038541200161305045","310038541200161305055","210038541200161305065","710038541200161306025","610038541200161306035","310038541200161301015","210038541200161301025","910038541200161301045","810038541200161301055","510038541200161306045","410038541200161306055","310038541200161306065","110038541200161301035","710038541200161301065","210038541200161302035","810038541200161302065","310038541200161303035","110038541200161303055","810038541200161306015"};
List<String> entries = java.util.Arrays.asList(array);
ExecutorService service = Executors.newFixedThreadPool(entries.size());
List<CompletableFuture<String>> completableFutures = entries.stream()
.map((entry) -> {
return CompletableFuture.supplyAsync(() -> {
try {
System.out.println(Thread.currentThread().getId()+ ": begin " + new Date() );
Thread.sleep(new Random().nextInt(5000) + 500);
System.out.println(Thread.currentThread().getId()+ ": end " + new Date() +" " + entry );
} catch (InterruptedException e) {
e.printStackTrace();
}
return Thread.currentThread().getId()+ " finished " + entry +" : " + new Date()+"; \r\n";
}, service);
}
).collect(Collectors.toList());
//线程的执行结果
StringBuffer sb = new StringBuffer();
//线程聚合等待
CompletableFuture
.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]))
.thenApply((v) -> completableFutures.stream().map((cf) -> cf.join()))
.get()
.forEach(sb::append);
//关闭线程池
service.shutdown();
assertNotNull(sb);
}