Java 多线程并行管理

Java 多线程并行管理工具类

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ThreadUtil {

	/** 线程池 线程数 */
	private static final int THREAD_POOL_SIZE = 5;

	/**
	 * 操作并行处理完成返回
	 * 
	 * @param <T>
	 * @param name
	 * @param list
	 * @param groupSize
	 * @param helper
	 */
	public static <T> void execute(String name, List<T> list, int groupSize, IRunHelper<T> helper) {
		ExecutorService executorService = null;
		try {
			List<List<T>> split = splitList(list, groupSize);
			int size = split.size();
			log.info("Count:{}", size);
			// 开始操作多线程,并添加门闩
			CountDownLatch countDownLatch = new CountDownLatch(size);
			executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

			Iterator<List<T>> iterator = split.iterator();
			boolean hasNext = iterator.hasNext();
			while (hasNext) {
				List<T> next = iterator.next();
				executorService.submit(new Runner<T>(name, next, countDownLatch, helper));
				hasNext = iterator.hasNext();
			}

			// 所有门闩打开后继续
			countDownLatch.await();
			log.info("{} Complete!", name);
		} catch (InterruptedException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (!(null == executorService || executorService.isShutdown())) {
				executorService.shutdown();
			}
		}

	}

	private static <T> List<List<T>> splitList(List<T> list, int groupSize) {
		int size = list.size();
		int limit = (size + groupSize - 1) / groupSize;
		return Stream.iterate(0, n -> n + 1).limit(limit).parallel()
				.map(a -> list.stream().skip(a * groupSize).limit(groupSize).parallel().collect(Collectors.toList()))
				.collect(Collectors.toList());
	}

	/**
	 * 业务逻辑执行注入
	 * 
	 * @author jun.chen
	 *
	 * @param <T>
	 */
	public static interface IRunHelper<T> {

		/**
		 * 具体操作
		 * 
		 * @return
		 */
		void operate(String name, List<T> list);
	}

	static class Runner<T> implements Runnable {

		private String name;

		private List<T> list;

		private CountDownLatch countDownLatch;

		private IRunHelper<T> helper;

		public Runner(String name, List<T> list, CountDownLatch countDownLatch, IRunHelper<T> helper) {
			this.name = name;
			this.list = list;
			this.countDownLatch = countDownLatch;
			this.helper = helper;
		}

		@Override
		public void run() {
			try {
				Thread currentThread = Thread.currentThread();
				String currentName = String.format("%s_%s_%s", this.name, currentThread.getName(),
						currentThread.getId());
				this.helper.operate(currentName, this.list);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			} finally {
				// 打开门闩
				this.countDownLatch.countDown();
			}

		}
	}

	public static void main(String[] args) {
		int i = 0;
		int groupSize = 4;
		while (i < 5) {
			List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
					"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O");
			ThreadUtil.execute("Test" + "-" + i, list, groupSize, new IRunHelper<String>() {

				@Override
				public void operate(String name, List<String> list) {
					log.info("Thread:{} Size:{} Info:{}", name, list.size(),
							String.join(",", list.toArray(new String[0])));
				}

			});

			i++;
		}
	}

}

有好的见解,欢迎留言 ^_^

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艮木@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值