为了账号安全,请及时绑定邮箱和手机立即绑定

如何将矩阵的不同行传递给线程池。

如何将矩阵的不同行传递给线程池。

炎炎设计 2023-06-21 15:39:30
我试图获得一个由 n 个线程组成的线程池来计算矩阵每一行的值并返回一个新的。到目前为止,我得到的代码的工作是创建线程并为需要完成的任务奠定基础,但我不确定如何为每个线程传递同一矩阵的不同行。例如,如果它是一个 3x3 矩阵,我们将有 3 个线程。第一个线程 -> 获取矩阵的第一条水平线,计算并更改值,将其添加到新矩阵第二个线程 -> 获取矩阵的第二条水平线...第 3 个线程 -> ...ExecutorService threadPool = Executors.newFixedThreadPool(n)    for(int i = 0; i < n; i++) {        threadPool.submit(new Runnable() {            public void run() {                  //take row of matrix                  //compute new row                  //add to result matrix                    }                    });                }    threadPool.shutdown();    threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
查看完整描述

1 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

int[][] array = new int[N][M]利用二维数组调用array[n]将返回第 n 行的事实,您可以将该行传递给每个线程:


int[][] array = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12,13,14,15} };


ExecutorService threadPool = Executors.newFixedThreadPool(array.length);

for(int i = 0; i < array.length; i++) {

    final int finalI = i;

    threadPool.submit(() -> {

        int[] row = array[finalI];

        System.out.println(Thread.currentThread().getName() + ": " + Arrays.toString(row));

        for(int j = 0; j < row.length; j++) {

            row[j] *= 2;

        }

    });

}


threadPool.shutdown();

while(!threadPool.isTerminated()) {

    Thread.sleep(20);

}


for(int i = 0; i < array.length; i++) {

    int[] row = array[i];

    for(int j = 0; j < row.length; j++) {

        System.out.print(row[j] + ", ");

    }

    System.out.println();

}

将打印:


pool-1-thread-4: [10, 11, 12, 13, 14, 15]

pool-1-thread-1: [1, 2, 3]

pool-1-thread-2: [4, 5, 6]

pool-1-thread-3: [7, 8, 9]

2, 4, 6, 

8, 10, 12, 

14, 16, 18, 

20, 22, 24, 26, 28, 30,


查看完整回答
反对 回复 2023-06-21
  • 1 回答
  • 0 关注
  • 71 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信