有人可以帮帮我吗?我正在尝试使用线程进行矩阵乘法。这是我到目前为止: //更新
public class Multiplication {
public static final int NUM_OF_THREADS = 8;
public static final int MATRIX_SIZE = 1000;
public static void main(String args[]) throws InterruptedException {
long startTime = System.currentTimeMillis();
int MatrixA[][] = matrixGenerator();
int MatrixB[][] = matrixGenerator();
int m1rows = MatrixA.length;
int m1cols = MatrixA[0].length;
int m2cols = MatrixB[0].length;
int MatrixC[][] = new int[m1rows][m2cols];
ExecutorService pool = Executors.newFixedThreadPool(NUM_OF_THREADS);
for (int row1 = 0; row1 < m1rows; row1++) {
for (int col1 = 0; col1 < m1cols; col1++) {
pool.submit(new MultiplicationThreading(row1, col1, MatrixA, MatrixB, MatrixC));
}
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.DAYS);
long endTime = System.currentTimeMillis();
System.out.println("Calculated in "
+ (endTime - startTime) + " milliseconds");
}
public static int[][] matrixGenerator() {
int matrix[][] = new int[MATRIX_SIZE][MATRIX_SIZE];
Random r = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt(10000);
}
}
return matrix;
}
}
//我已经更新了代码 我现在得到更好的时间。当使用2个线程时,我得到1.5k毫秒,当我使用8个线程时,得到1.3k毫秒
答案 0 :(得分:1)
使用thrd
元素初始化NUM_THREADS == 9
数组。如果m1rows*m1cols
超过该值,您将遇到此问题,因为您尝试创建超过9个线程并将它们分配给该数组的元素。 (您正在尝试创建50个线程)。
两种解决方案:
thrd = new Thread[m1rows*m1cols]
List<Thread>
。请注意,您不会并行执行线程,因为您在调用Thread.join()
后立即调用Thread.start()
。这只会阻止当前线程,直到thrd[threadcount]
完成。
将Thread.join()
调用移动到一个单独的循环中,因此在您对其中任何一个调用join
之前,所有线程都已启动。
for (row = 0; row < m1rows; row++) {
for (col = 0; col < m1cols; col++) {
// creating thread for multiplications
thrd[threadcount] = new Thread(new MultiplicationThreading(row, col, MatrixA, MatrixB, MatrixC));
thrd[threadcount].start(); //thread start
threadcount++;
}
}
for (Thread thread : thrd) {
thread.join();
}