简单快速的数组反转。
思路:
1. 比如25个数5个线程,则线程 1 依次反转 0 <-> 24 (n-index-1), 5 <-> 19(n-index-1) , 10 <-> 14, 15 <-> 9 , 20 <-> 4
2. 对于剩余线程和 1 同理
线程2:1 <-> 23, . . . . ,
线程3: 2 <-> 22 . . . . .,
线程4:3 <-> 22, . . . . ,
线程5: 4 <-> 21 . . . . .
package com.jie.javaConcurrencyInPractice;
/**
* @author JayDing
* @description
* @date 2023/5/25
*/
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class ThreadPoolTest {
static int coreSize = Runtime.getRuntime().availableProcessors();
static ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, coreSize, 1,
TimeUnit.MINUTES, new SynchronousQueue<>(true));
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
reverse(arr, 5);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
public static void reverse(int[] arr, int threadCount) {
if (arr == null || arr.length <= 1 || threadCount <= 0) {
return;
}
int len = arr.length;
if (len == 2 || len == 3) {
swap(arr, 0, len - 1);
}
int realThreadCount = threadCount < len ? threadCount : len;
for (int i = 0; i < realThreadCount; i++) {
int currentIndex = i;
executor.execute(new Runnable() {
int index = currentIndex;
@Override
public void run() {
while (index < len / 2) {
swap(arr, index, len - index - 1);
index += realThreadCount;
}
}
});
}
executor.shutdown();
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}