【高并发系列】25、并行搜索

简单的策略实现并行搜索:

将原始数据集合按照期望的线程数量分割;每个线程各自独立搜索,当其中有一个线程找到数据后,立即返回结果即可;

/**
 * 并行搜索
 * 
 * @author daniel
 */
public class ParallelSearch {
	// 整型数组,保存需要查找的元素
	static int[] arr;
	// 线程池
	static ExecutorService pool = Executors.newCachedThreadPool();
	// 线程数量
	static final int Thread_num = 2;
	// 结果,默认-1表示未找到
	static AtomicInteger result = new AtomicInteger(-1);
	/**
	 * 每个线程实际执行的搜索方法
	 * 
	 * @param searchValue
	 *            要查找的数据
	 * @param beginPos
	 *            开始位置
	 * @param endPos
	 *            结束位置
	 * @return 查找数据所在位置或未找到-1
	 */
	public static int search(int searchValue, int beginPos, int endPos) {
		int i = 0;
		for (i = beginPos; i < endPos; i++) {
			// 其他线程已经找到查找的数据
			if (result.get() >= 0) {
				return result.get();
			}
			// 本线程找到查找的数据
			if (arr[i] == searchValue) {
				// 设置失败表示其他线程已经找到
				if (!result.compareAndSet(-1, i)) {
					return result.get();
				}
				return i;
			}
		}
		return -1;
	}
	/**
	 * 查找任务类
	 * 
	 * @author daniel
	 */
	public static class SearchTask implements Callable<Integer> {
		int begin, end, searchValue;
		public SearchTask(int searchValue, int begin, int end) {
			this.searchValue = searchValue;
			this.begin = begin;
			this.end = end;
		}
		@Override
		public Integer call() throws Exception {
			int re = search(searchValue, begin, end);
			return re;
		}
	}
	/**
	 * 封装的查找方法
	 * 
	 * @param searchValue
	 *            要查找的数据
	 * @return 查找数据所在位置或未找到-1
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public static int pSearch(int searchValue) throws InterruptedException, ExecutionException {
		int subArrSize = arr.length / Thread_num + 1;
		List<Future<Integer>> re = new ArrayList<>();
		for (int i = 0; i < arr.length; i += subArrSize) {
			int end = i + subArrSize;
			if (end >= arr.length) {
				end = arr.length;
			}
			re.add(pool.submit(new SearchTask(searchValue, i, end)));
		}
		for (Future<Integer> fu : re) {
			if (fu.get() >= 0) {
				return fu.get();
			}
		}
		return -1;
	}
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		arr = new int[] { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
		System.out.println(pSearch(4));
		pool.shutdown();
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值