標籤:tac oid 影響 pack col color trace ext 記錄
Program:多線程矩陣相乘演算法的設計
Description:利用多線程實現矩陣相乘,因為各個線程的運算互不影響,
所以不用使用鎖,代碼如下:
thread.OperateMatrix類,實現矩陣運算
1 /* 2 * Description:定義矩陣操作類 3 * 4 * Written By :Cai 5 * 6 * Date Written:2017-10-25 7 * 8 * */ 9 10 package thread;11 12 public class OperateMatrix {13 14 int[][] matrix1 = null; //第一個矩陣15 int[][] matrix2 = null; //第二個矩陣16 int[][] result = null; //存放矩陣相乘結果17 public static int line = 0; //記錄當前參與計算的是第一個矩陣的第幾行18 19 //定義構造方法20 public OperateMatrix() {}21 22 public OperateMatrix(int[][] m1,int[][] m2) {23 24 this.matrix1 = m1;25 this.matrix2 = m2;26 result = new int[matrix1.length][matrix2[0].length];27 }28 29 //返回矩陣相乘的結果30 public int[][] getResult() {31 32 try {33 34 /*35 * 當矩陣還沒有完全計算完時36 * 令當前線程睡眠1毫秒等待37 * 然後再次判斷38 * 39 * */40 while( OperateMatrix.line < matrix1.length ) {41 42 Thread.sleep(1);43 44 }45 }catch(Exception e) {46 47 e.printStackTrace();48 }49 50 return this.result;51 52 }53 54 //第一個矩陣的行乘以第二個矩陣的列,得到新矩陣的行55 public void operate() {56 57 OperateMatrix.line += 1; //記錄行數加158 59 for( int i = 0; i < matrix1[0].length; i++ ) {60 61 int sum = 0; //儲存第一個矩陣的行和 第二個矩陣的列的計算結果62 for( int j = 0; j < matrix2.length; j++ ) {63 64 sum += matrix1[OperateMatrix.line - 1][j] * matrix2[j][i]; //第一個矩陣的當前行乘以第二個矩陣65 }66 67 result[OperateMatrix.line - 1][i] = sum; //儲存結果68 }69 70 }71 }
thread.ThreadOperate類,線程實作類別
1 /* 2 * Description:定義類,繼承Thread類,覆寫run()方法 3 * 4 * Written By:Cai 5 * 6 * Date Written:2017-10-25 7 * 8 * */ 9 10 package thread;11 12 public class ThreadOperate extends Thread {13 14 private OperateMatrix om = null; //定義矩陣操類對象15 16 //定義構造方法17 public ThreadOperate() {18 super();19 }20 21 public ThreadOperate( OperateMatrix om,String name) {22 super(name); //線程名字23 this.om = om;24 }25 26 //覆寫run()方法27 @Override28 public void run() {29 30 try {31 System.out.println( Thread.currentThread().getName() ); //列印當前線程的名字32 }catch( Exception e ) {33 e.printStackTrace();34 }35 36 /*37 * 調用OperateMatrix對象的operate方法,進行矩陣的計算38 * 每次調用只計算一行結果39 * 40 * */41 this.om.operate(); 42 }43 44 }
main.TestDemo測試類別
1 /* 2 * Description:定義測試類別 3 * 4 * Written By :Cai 5 * 6 * Date Written:2017-10-25 7 * 8 * */ 9 10 11 package main;12 13 14 import thread.*;15 16 public class TestDemo {17 18 public static void main(String args[]) {19 20 //定義兩個矩陣21 int[][] m1 = {{1,4,1,1},{4,1,1,1},{1,3,3,6},{1,6,9,0}}; //4*422 int[][] m2 = {{2,2,2,2},{2,2,2,2},{2,2,2,2},{2,2,2,2}}; //4*423 24 OperateMatrix om = new OperateMatrix(m1,m2); //執行個體化OperateMatrix對象25 26 //根據第一個矩陣的行數,啟動對應數量的線程27 for( int i = 0; i < m1.length; i++ ) {28 29 new ThreadOperate( om,"計算第一個矩陣的第" + (i+1) + "行*第二個矩陣的所有列" ).start();30 }31 32 33 display(om.getResult()); //列印結果34 35 }36 37 38 //列印計算結果(為了方便,將列印方法定義在測試類別中,實際不應該這樣做)39 public static void display(int[][] result) {40 41 for( int i = 0; i < result.length; i++ ) {42 43 for( int j = 0; j < result[i].length; j++ ) {44 45 System.out.print( result[i][i] + "\t" );46 }47 48 System.out.println();49 }50 }51 52 }
Java實驗項目四——多線程矩陣相乘演算法的設計