1 需要线程返回信息
public void execute(){
//来一个线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture<Integer> future1= CompletableFuture.supplyAsync(new Supplier<Integer>()
{
@Override
public Integer get() {
for(int i=0;i<10;i++) {
System.out.println("task1:"+i);
sleep(1000);
}
return 333;
}
},executor);
CompletableFuture<Integer> future2 =CompletableFuture.supplyAsync(new Supplier<Integer>()
{
@Override
public Integer get() {
for(int i=0;i<10;i++) {
System.out.println("task2:"+i);
sleep(1000);
}
return 666;
}
},executor);
//等待所有任务执行结束
CompletableFuture<Void> all= CompletableFuture.allOf(future1,future2);
all.thenAccept(e->{
//关闭线程池
executor.shutdown();
System.out.println("执行结束");
});
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2 仅执行
//线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture<Void> future1= CompletableFuture.runAsync(()->{
},executor);
CompletableFuture<Void> future2 =CompletableFuture.runAsync(()->{
},executor);
//等待完成
try {
CompletableFuture.allOf(future1,future2).get();
}
catch (InterruptedException|ExecutionException e ) {
e.printStackTrace();
}
executor.shutdown();
System.out.println("执行完毕");
线程池执行业务,模板
@Test
public void test() {
// 开50线程执行
ExecutorService executor = Executors.newFixedThreadPool(50);
//计数器
AtomicInteger cnt = new AtomicInteger(0);
//业务数据
List<String> list = new ArrayList<>();
for (int i = 0; i < 99; i++) {
list.add("sss" + i + 1);
}
// 阻塞线程计数器
CountDownLatch countDownLatch = new CountDownLatch(list.size());
for (String s : list) {
// 异步执行
executor.execute(() -> {
// do something
try {
System.out.println("第" + cnt.getAndAdd(1) + "个,ok,"+s);
} catch (Exception e) {
System.out.println("第" + cnt.getAndAdd(1) + "个失败,"+s);
} finally {
countDownLatch.countDown();
}
});
}
// countDownLatch计数阻塞
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("===结束===");
// 关闭线程池
executor.shutdown();
}