簡體   English   中英

從文件中讀取矩陣,與多線程相乘

[英]Matrix reading from file, multiplication with multithreading

我有一個從文件中讀取兩個矩陣的代碼,將其相乘,然后將結果寫入文件。 我想修改它,所以它對所有這些操作(讀取、乘法、寫入等)使用多線程。 我怎么解決這個問題? 這就是我現在所擁有的。

file1.txt
4 3 4 6
-1 10 4 -1
4 7 2 -8

file2.txt
3 0 0
0 3 0
0 0 3
0 2 4



 public static void main(String[] args) throws IOException {
        String file1 = "file1.txt";
        String file2 = "file2.txt";

        List<ArrayList<Integer>> matrix1 = readFile(file1);
        List<ArrayList<Integer>> matrix2 = readFile(file2);

        int[][] result = multiplyMatrix(matrix1, matrix2);

        writetoFile(result);


    }

    public static int[][] multiplyMatrix(List<ArrayList<Integer>> matrix1, List<ArrayList<Integer>> matrix2) {
//I have implementation
        return result;
    }


    public static void writetoFile(int[][] matrix) {
       //I have implementation
    }

    public static List<ArrayList<Integer>> readFile(String filename) throws IOException {
      //I have implementation
        return a;
    }

如果您想提高性能,那么多線程讀寫將無濟於事。 因為只有一個線程應該寫入文件以防止內容損壞。 多線程讀取的一種可能解決方案是逐行讀取,但在讀取之前我們不知道總行數。 多線程計算可以這樣完成

public List<List<Integer>> multiply(List<List<Integer>> matrix1, List<List<Integer>> matrix2) {
    List<List<Integer>> result;
    List<List<Integer>> matrix2T = matrix2.transpose();
    Collection<CompletableFuture> futures = new ArrayList<>();
    for(int i = 0, n = matrix1.size(); i < n; i++) {
        for (int j = 0, m = matrix2.size(); j < m; j++) {
            futures.add(CompletableFuture.runAsync(() -> multiply(matrix1, matrix2T, result, i, j)));
        }
    }
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM