Skip to content

Instantly share code, notes, and snippets.

@jhead
Created March 26, 2013 19:02
Show Gist options
  • Save jhead/5248183 to your computer and use it in GitHub Desktop.
Save jhead/5248183 to your computer and use it in GitHub Desktop.
/**
* Multi-threaded matrix multiplication.
* @param a a matrix
* @param b another matrix
* @return The resulting matrix-multiplied matrix
*/
public static int[][] multiplyMatrix(final int[][] a, final int[][] b) {
ExecutorService exec = Executors.newFixedThreadPool(9);
List<Callable<Object>> tasks = new LinkedList<>();
final int[][] result = new int[3][3];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result.length; j++) {
final int x = i;
final int y = j;
tasks.add(Executors.callable(new Runnable() {
@Override
public void run() {
for (int k = 0; k < a[x].length; k++) {
result[x][y] += a[x][k] * b[k][y];
}
}
}));
}
}
try {
exec.invokeAll(tasks);
exec.shutdown();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment