Java利用Callable和Future进行并行搜索
public class Search {
static int[] array = new int[1000000];
static int Thread_num = 100;
static AtomicInteger result = new AtomicInteger(-1);
static ExecutorService pool = Executors.newCachedThreadPool();
public static int search(int value,int begin,int end) {
int i=0;
for( i=begin;i<end;i++) {
if (result.get()>=0) {
return result.get();
}
if (array[i]==value) {
if (!result.compareAndSet(-1,i)) {
return result.get();
}
return i;
}
}
return -1;
}
public static class searchTask implements Callable<Integer>{
int begin,end,value;
public searchTask(int value,int begin,int end) {
this.begin=begin;
this.end=end;
this.value=value;
}
@Override
public Integer call() throws Exception {
int re = search(value, begin, end);
return re;
}
}
public static void pSearch(int value) throws InterruptedException, ExecutionException {
for(int i=0;i<1000000;i++) {
array[i] = i;
}
int size = array.length/2+1;
List<Future<Integer>> re = new ArrayList<>();
for(int i=0;i<array.length;i+=size) {
int end = i+size;
if (end>=array.length) {
end=array.length;
}
re.add(pool.submit(new searchTask(value, i, end)));
}
for(Future<Integer> fu:re) {
if (fu.get()>=0) {
System.out.println(fu.get());
}
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
long start = System.currentTimeMillis();
Search search = new Search();
search.pSearch(999999);
System.out.println(System.currentTimeMillis()-start);
}
}