简单的策略实现并行搜索:
将原始数据集合按照期望的线程数量分割;每个线程各自独立搜索,当其中有一个线程找到数据后,立即返回结果即可;
/**
* 并行搜索
*
* @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();
}
}