亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將矩陣的不同行傳遞給線程池。

如何將矩陣的不同行傳遞給線程池。

炎炎設計 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();

}

將打?。?/p>


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 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號