07.03.2014 Views

Programowanie współbieżne w języku Java

Programowanie współbieżne w języku Java

Programowanie współbieżne w języku Java

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Mnożenie macierzy – trzy wersje (książkowa – naiwna, z biblioteki Jama, wielowątkowa).<br />

package mmold;<br />

import java.util.concurrent.ExecutorService;<br />

import java.util.concurrent.Executors;<br />

import java.util.concurrent.TimeUnit;<br />

public class MatrixMultiply02 {<br />

public static void main(String[] args) {<br />

int m = 6;<br />

int n = 7;<br />

int k = 8;<br />

double[][] a = new double[m][n];<br />

double[][] b = new double[n][k];<br />

double[][] c = new double[m][k];<br />

for (int i = 0; i < m; ++i) {<br />

for (int j = 0; j < n; ++j) {<br />

a[i][j] = 1.0D;<br />

}<br />

}<br />

for (int i = 0; i < n; ++i) {<br />

for (int j = 0; j < k; ++j) {<br />

b[i][j] = 1.0D;<br />

}<br />

}<br />

System.out.println("=== First (naive method) test ===");<br />

printMatrix(a, m, n, "A");<br />

printMatrix(b, n, k, "B");<br />

naiveMatrixMultiply(a, b, c);<br />

printMatrix(c, m, k, "C");<br />

System.out.println("=== Second (jama method) test ===");<br />

printMatrix(a, m, n, "A");<br />

printMatrix(b, n, k, "B");<br />

jamaMatrixMultiply(a, b, c);<br />

printMatrix(c, m, k, "C");<br />

}<br />

System.out.println("=== Third (threaded - Executors) test ===");<br />

printMatrix(a, m, n, "A");<br />

printMatrix(b, n, k, "B");<br />

threadedMatrixMultiply(a, b, c, 2);<br />

printMatrix(c, m, k, "C");<br />

// book like method matrix multiplication - matrix indexing is very slow<br />

static void naiveMatrixMultiply(final double[][] a, final double[][] b,<br />

final double[][] c) {<br />

// check(a,b,c); // checks for null args, incorrectly sized matrices,<br />

etc.<br />

final int m = a.length;<br />

final int n = b.length;<br />

final int p = b[0].length;<br />

for (int j = 0; j < p; j++) {<br />

for (int i = 0; i < m; i++) {<br />

double s = 0;<br />

for (int k = 0; k < n; k++) {<br />

s += a[i][k] * b[k][j];<br />

}<br />

c[i][j] = s;<br />

}<br />

}<br />

}<br />

// Jama multiplication - much faster vector indexing than double array<br />

indexing<br />

static void jamaMatrixMultiply(final double[][] a, final double[][] b,<br />

Lab. „<strong>Programowanie</strong> <strong>współbieżne</strong> w <strong>języku</strong> <strong>Java</strong>”<br />

17

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!