Java-多线程反转数组

该博客介绍了一个使用Java实现的多线程数组反转方法。根据数组长度和给定线程数量,智能地创建线程,每个线程负责数组中对应位置的元素交换。当线程完成任务后,数组实现反转。示例代码展示了如何利用ThreadPoolExecutor和CountDownLatch来协调多线程操作。

题目
 给定一个整型数组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());
    }
}

 

### Java 中通过字符数组反转字符串 在 Java 中,可以通过操作字符数组来实现字符串的反转。以下是基于字符数组的具体实现方式: #### 方法描述 该方法的核心思想是将输入字符串转换为字符数组,随后利用双指针技术交换首尾字符并逐步向中心靠拢,最终完成整个字符串的反转。 #### 实现代码 以下是一个完整的示例代码,展示如何使用字符数组实现字符串反转功能: ```java public class ReverseString { public static String reverseUsingCharArray(String input) { if (input == null || input.isEmpty()) { return input; } char[] characters = input.toCharArray(); // 将字符串转换为字符数组 [^1] int left = 0; // 定义左指针 int right = characters.length - 1; // 定义右指针 while (left < right) { // 当左指针小于右指针时执行循环 // 交换两个位置上的字符 char temp = characters[left]; characters[left] = characters[right]; characters[right] = temp; left++; // 左指针向前移动一位 right--; // 右指针向后移动一位 } return new String(characters); // 转换回字符串并返回结果 } public static void main(String[] args) { String original = "hello world"; String reversed = reverseUsingCharArray(original); System.out.println("Original: " + original); // 输出原始字符串 System.out.println("Reversed: " + reversed); // 输出反转后的字符串 } } ``` 上述代码展示了如何手动处理字符数组以达到字符串反转的目的。此方法相较于 `StringBuilder.reverse()` 更加底层,适合用于学习基础原理或特定需求下的优化场景[^2]。 #### 性能分析 相比内置函数如 `StringBuilder.reverse()` 的高效率和简洁性,这种方法虽然稍显复杂,但在某些特殊场合下可能提供更灵活的操作能力。例如,在多线程环境中或者需要自定义逻辑的情况下,这种手写的方式可能会更加实用。 ---
评论 6
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值