线程池并行执行逻辑代码块Demo示例(await同步)

应用场景:

某段代码for循环执行特别慢 , 用多线程并行执行会提高效率;
要求全部线程执行完时 , 程序才能继续往下执行;
多线程执行过程中 , 记录执行结果追加到某个变量上 , 后续逻辑要用

代码示例:

public class NwdTest {
	//线程计数器,用于判断当所有线程都执行完的时机
    static CountDownLatch latch = null;
    public static void main(String[] args) throws InterruptedException {
		//创建线程池
		ThreadPoolExecutor executor = new ThreadPoolExecutor(20,
		21,
		3600, 
		TimeUnit.SECONDS,
		new LinkedBlockingQueue(1000),
                new CustomizableThreadFactory("wave"));
         //sBuffer模拟业务逻辑操作对象
        StringBuffer strBuffer = new StringBuffer();
        //线程同步计数器
        latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            String tmp = i+"";
            CompletableFuture future = CompletableFuture
           		 .runAsync(() -> {
                        try {
                            //处理逻辑
                            strBuffer .append(tmp+";");
                            //打印当前执行线程的名称
                            System.out.println(Thread.currentThread().getName());
                         } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            latch.countDown();
                        }
                  },executor)
                    .exceptionally(e -> {
                        System.out.println("发生异常");
                  		return null;
                    });
         }
         latch.await();
        System.out.println("逻辑执行结果:"+strBuffer);       
	}
}

你可能感兴趣的:(java)