第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

炎炎設(shè)計 2023-06-21 15:39:30
我試圖獲得一個由 n 個線程組成的線程池來計算矩陣每一行的值并返回一個新的。到目前為止,我得到的代碼的工作是創(chuàng)建線程并為需要完成的任務(wù)奠定基礎(chǔ),但我不確定如何為每個線程傳遞同一矩陣的不同行。例如,如果它是一個 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 回答

?
呼啦一陣風(fēng)

TA貢獻(xiàn)1802條經(jīng)驗 獲得超6個贊

int[][] array = new int[N][M]利用二維數(shù)組調(diào)用array[n]將返回第 n 行的事實(shí),您可以將該行傳遞給每個線程:


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,


查看完整回答
反對 回復(fù) 2023-06-21
  • 1 回答
  • 0 關(guān)注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號