多线程反转数组

 简单快速的数组反转。

思路:

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值