猿问

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

我试图获得一个由 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);


炎炎设计
浏览 96回答 1
1回答

呼啦一阵风

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++) {&nbsp; &nbsp; final int finalI = i;&nbsp; &nbsp; threadPool.submit(() -> {&nbsp; &nbsp; &nbsp; &nbsp; int[] row = array[finalI];&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Thread.currentThread().getName() + ": " + Arrays.toString(row));&nbsp; &nbsp; &nbsp; &nbsp; for(int j = 0; j < row.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row[j] *= 2;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}threadPool.shutdown();while(!threadPool.isTerminated()) {&nbsp; &nbsp; Thread.sleep(20);}for(int i = 0; i < array.length; i++) {&nbsp; &nbsp; int[] row = array[i];&nbsp; &nbsp; for(int j = 0; j < row.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(row[j] + ", ");&nbsp; &nbsp; }&nbsp; &nbsp; 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,&nbsp;8, 10, 12,&nbsp;14, 16, 18,&nbsp;20, 22, 24, 26, 28, 30,
随时随地看视频慕课网APP

相关分类

Java
我要回答