题目
给定一个整型数组int[] arr,使用threadCounts个线程对该数组中的元素进行反转。
分析
1.假设数组长度为n,反转的原理是将第i个元素和第(n - 1 - i)个元素进行交换。
2.如果数组arr为空或者长度为0或者1,直接返回当前数组即可,不需要进行交换。
3.如果数组arr的长度为2或者3,那么只需要将第1个元素和最后一个元素交换即可,不需要创建多个线程。
4.如果给定线程数量threadCounts小于数组的长度arrLen,那么创建threadCounts个线程,否则只创建arrLen个线程。
5.假设给线程标号为0 ~(threadCounts - 1),那么每个线程交换的元素为threadIndex,threadIndex + threadCounts * i,直到(threadIndex + threadCounts * i)大于等于arrLen / 2为止,比如第0个线程只操作第0,0 + threadCounts * i位置的元素交换。
6.多个线程都操作完,反转结束。
代码如下
package com.sw.leetcodetest;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class ThreadPoolTest {
static int corePoolSize = Runtime.getRuntime().availableProcessors();
static ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, corePoolSize, 1, TimeUnit.MINUTES, new SynchronousQueue<Runnable>(true));
public static void main(String[] args) {
// int[] arr = new int[]{0, 1, 2, 3};
int[] arr = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};
int[] reverse = reverse(arr, 5);
print(reverse);
}
private static int[] reverse(final int[] arr, final int threadCounts) {
if (arr == null || arr.length <= 1 || threadCounts <= 0) {
return arr;
}
final int arrLen = arr.length;
if (arrLen == 2 || arrLen == 3) {
return swap(arr, 0, arrLen - 1);
}
try {
int realThreadCounts = threadCounts < arrLen ? threadCounts : arrLen;
final CountDownLatch countDownLatch = new CountDownLatch(realThreadCounts);
for (int i = 0; i < realThreadCounts; i++) {
final int currentIndex = i;
executor.execute(new Runnable() {
@Override
public void run() {
int index = currentIndex;
while (index < arrLen / 2) {
swap(arr, index, arrLen - 1 - index);
index += realThreadCounts;
}
System.out.println("thread_" + currentIndex + " complete");
countDownLatch.countDown();
}
});
}
countDownLatch.await(100, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
private static int[] swap(int[] arr, int lIndex, int rIndex) {
int temp = arr[lIndex];
arr[lIndex] = arr[rIndex];
arr[rIndex] = temp;
return arr;
}
private static void print(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int i : arr) {
sb.append(i).append(",");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
System.out.println(sb.toString());
}
}