用多线程计算两个大向量的乘积
想问大家一个问题 如何分别用4,128个线程计算两个向量的乘积 每个向量1000个元素 array1=(a1,..a1000), array2=(b1,...b1000)
P=array1 * array2=a1*b1+...a1000*b1000
最好能给个代码段
万分感谢 再万分感谢
------解决方案--------------------例子,可能有错误。
能跑出结果 length太大的话可能会 heap 溢出。
加大内存空间,或者在这个基础上改进一下吧。
public class TArray {
//number of thread
private static int threadNum = 10;
//length of array
private static int arrayLength = 100000;
public static void main(String args[]){
TArray service = new TArray();
int[] a = service.createArray(arrayLength);
int[] b = service.createArray(arrayLength);
CalcArray[] calcServ = new CalcArray[threadNum];
int x = arrayLength / threadNum;
int idx = 0 ;
for(int i=0;i <threadNum-1;i++){
calcServ[i] = new CalcArray(a,b,idx,idx+=x);
}
calcServ[threadNum-1] = new CalcArray(a,b,idx,arrayLength-1);
for(int i=0;i <threadNum;i++){
calcServ[i].start();
}
for(int i=0;i <threadNum;i++){
try {
calcServ[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long sum = 0;
for(int i=0;i <threadNum;i++){
sum+=calcServ[i].getResult();
}
System.out.println( "sum= "+sum);
}
private int[] createArray(int length){
int[] a = new int[length];
for(int i=0;i <length;i++){
a[i] = i+1;
}
return a;
}
}
class CalcArray extends Thread{
private long result = 0;
private int[] a = null;
private int[] b = null;
private int index1 ,index2;
public CalcArray(int[] a , int[] b , int index1 , int index2){
this.a = a;
this.b = b;
this.index1 = index1;
this.index2 = index2;
}
public void run(){
for(int i=index1;i <index2;i++){
result+=a[i]*b[i];
}
}
public long getResult(){
return this.result;
}
}
------解决方案--------------------我给你写了一个,你可直接用. 写的比较乱,有些地方可以合并,比较两个wait. 为了说明问题,我给分开写了.
import java.util.Vector;
public class T2 {
int backNum=0;
//定义线程类
class AddThread extends Thread{
T2 t2;
int a = 0;
int b = 0;
int result = 0;
AddThread(T2 t2,int a,int b){
this.t2 = t2;
this.a = a;
this.b = b;
}
public void run() {
result = a*b;
System.out.println( "a= "+a+ "\tb= "+b+ "\tresult= "+result);
t2.callBack(result);
}
}
int maxThreadNum = 4; //定义要开启的线程数
int threadDegree = 0; //当前是有几个线程在运行
int sumResult = 0; //最终的相加结果
// 回调方法
public synchronized void callBack(int result){
sumResult = sumResult + result;
threadDegree--;
release(); //唤醍主线程
}
//释放等待线程
public synchronized void release() {
notifyAll();
}
//判断多线程是否执行完,如果没有就等待,如果执行完就返回
public synchronized int waitResult(){
int len = v1.size();
int i = 0;