CountDownLatch是java中一个协调多线程的工具类,假如多线程在执行后,需要等待所有都执行完再执行下一步,那么就可以使用CountDownLatch。
比如将会有10个线程,那么可以CountDownLatch latch =new CountDownLatch(10),在每个线程内减少值(latch.countDown()),在下面就可以使用latch.await()方法等待所有线程都执行完成,才继续执行下去。还可以将多线程内报的错误带出来,详情见代码中AtomicReference> exe =new AtomicReference<>(new ArrayList<>());
public void excuteThread(int num)throws Throwable {
MyThreadConfig threadConfig =new MyThreadConfig();
ThreadPoolTaskExecutor executor = threadConfig.taskExecutor();
int excuteTimes = num /10;
CountDownLatch latch =new CountDownLatch(excuteTimes);
AtomicInteger count =new AtomicInteger(0);
AtomicReference<List<Exception>> exe = new AtomicReference<>(new ArrayList<>());
for (int i =0; i < excuteTimes; i++) {
int finalI = i;
executor.execute(() -> {
Thread.currentThread().setName("thread-" +finalI);
System.out.println(Thread.currentThread().getId());
System.out.println(Thread.currentThread().getName() +" sleep begin");
try {
Thread.sleep(500);
if (finalI ==0) {
throw new RuntimeException("第0个的错");
}
if (finalI ==1) {
throw new RuntimeException("第1个的错");
}
if (finalI ==2) {
throw new RuntimeException("第2个的错");
}
if (finalI ==4) {
int a =1 /0;
}
count.incrementAndGet();
}catch (Exception e) {
e.printStackTrace();
exe.get().add(e);
}finally {
latch.countDown();
}
System.out.println(Thread.currentThread().getName() +"sleep over");
});
}
latch.await();
if (count.get() != excuteTimes) {
exe.get().forEach(e -> {
e.printStackTrace();
});
throw new RuntimeException("多线程内部报错了!");
}
System.out.println("顺利执行完成!");
}
网友评论