多线程解决多数组元素反转问题
该题属于自由市场中,某大厂的笔试题
题目内容
对多个String数组中,指定位置范围内的数字进行反转后,输出合并所有数组后的字符串。要求用多线程解决该问题
思路与代码
要求多线程考虑使用数量为数组数量的固定线程池,要求返回字符串结果,所以考虑使用具有返回值的Callable。代码如下:
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
/**
* 两个线程,将两个数组指定位置范围的数进行反转,并合并输出
* Created by yanzhang on 2020/3/17 15:32
*/
public class MultiReverseArray {
public static void main(String[] args) {
String result = "";
String[] arr1 = {"a","b","c","d","e","f","g"};
String[] arr2 = {"h","i","j","k","l","m","n"};
List<String[]> strings = Arrays.asList(arr1, arr2);
final int start = 3;
final int end = 5;
// List<Future<String>> reverseTaskFutureList = new ArrayList<>();
ExecutorService executorPool = Executors.newFixedThreadPool(2);
for(final String[] s: strings) {
Future<String> submit = executorPool.submit(new ReverseTask(s, start, end));
try {
result+=submit.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println(result);
// for(Future<String> future : reverseTaskFutureList) {
//
// }
executorPool.shutdown();
}
static class ReverseTask implements Callable<String> {
String[] arr;
int start;
int end;
ReverseTask(String[] arr,int start,int end) {
this.arr = arr;
this.start = start;
this.end = end;
}
@Override
public String call() throws Exception {
return reverseArr(arr,start,end);
}
/**
* 反转数组中指定范围的数字
**/
private String reverseArr(String[] arr,int start,int end) {
String str = "";
StringBuffer sb = new StringBuffer();
if(arr.length<start || end >arr.length)
return str;
for(int i=0;i<arr.length-1;i++) {
if(i<start) {
str+=arr[i];
} else if(i>=start && i<=end){
sb.append(arr[i]);
if(i==end) {
sb.reverse();
str+=sb.toString();
}
} else {
str+=arr[i];
}
}
return str;
}
}
}