//两个线程求数组最大值
public class FindMaxTarget implements Callable<Integer>{
int[] data;int start;
int end;
public FindMaxTarget(int[] data,int start,int end){
this.data=data;
this.start=start;
this.end=end;
}
@Override
public Integer call() throws Exception {
int max=Integer.MIN_VALUE;
for(int i=start;i<=end;i++){
if(data[i]>max){
max=data[i];
}
}
return max;
}
}
public class MultiThreadMaxFinder {
public static int max(int[] data) throws InterruptedException, ExecutionException{
if(data.length==1){
return data[0];
}else if(data.length==0){
throw new IllegalArgumentException();
}
int mid=data.length/2;
FindMaxTarget task1=new FindMaxTarget(data,0,mid);
FindMaxTarget task2=new FindMaxTarget(data,mid+1,data.length-1);
ExecutorService service=Executors.newFixedThreadPool(2);
Future<Integer> future1=service.submit(task1);
Future<Integer> future2=service.submit(task2);
return Math.max(future1.get(),future2.get());
}
}
public class MaxValueSolution {//测试类
public static void main(String[] args) {
int[] data={3,1,6,0,5,7,2,9,8};
MultiThreadMaxFinder mtmf=new MultiThreadMaxFinder();
int max;
try {
max = mtmf.max(data);
System.out.println("max="+max);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}