【发布时间】:2017-03-18 02:40:08
【问题描述】:
我正在尝试实现一个可以使用 Callable(线程池)进行矩阵乘法的程序。我在下面有这个程序。但是,当我在一个线程或 8 个线程上运行它时,我看不到执行时间有任何显着差异。
我为一个线程和 8 个线程取了 5 个样本,它们如下(均以毫秒为单位):
1 个线程 - 5433.982472、6872.947063、6371.205237、6079.367443、5842.946494
8 线程 - 5260.792683、5517.047691、5314.208147、5739.747367、5585.621661
我是新手,我做错了什么吗?
package naivematmul;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
class NaiveMatMul implements Callable<Integer>
{
private int n;
private int a[][];
private int b[][];
private int sum;
private int i;
private int j;
public NaiveMatMul(int n, int a[][], int b[][], int i , int j )
{
this.n = n;
this.a = a;
this.b = b;
this.i = i;
this.j = j;
this.sum = sum;
}
public Integer call() throws Exception
{
for (int k = 0 ; k < n ; k++)
{
sum = sum + a[i][k] * b[k][j];
}
return sum;
}
public static void main(String[] args) throws InterruptedException, ExecutionException
{
int n;
int[][] a, b, c;
n = 512;
a = new int[n][n];
b = new int[n][n];
c = new int[n][n];
int threads = 8;
ExecutorService executor = Executors.newFixedThreadPool(threads);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
a[i][j] = 1;
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
b[i][j] = 1;
}
}
int sum = 0;
long start_time = System.nanoTime();
Future<Integer> future;
for (int i = 0; i < n ; i++)
{
for (int j = 0 ; j < n ; j++)
{
future = executor.submit(new NaiveMatMul(n, a, b, i, j));
c[i][j] = future.get();
sum = 0;
}
}
long end_time = System.nanoTime();
double difference = (end_time - start_time)/1e6;
executor.shutdown();
System.out.println("Time taken : " + difference);
}
}
【问题讨论】:
标签: java multithreading matrix-multiplication