我正在尝试使用协作线程添加一个2D数组。但我只得到了最后一条线的答案。我只有3条线。我的代码是:
public class Arr2DThreadAdd {
static int[ ] [ ] arr2D ={{10, 20, 30, 40}, {11, 12, 13, 14}, {12, 13, 14, 15}};
static int[ ] result = new int[3];
static class job extends Thread{
int arr2Mindex;
job(int index){
arr2Mindex= index;
}
public void run(){
int i;
int sum=0;
for( i=0;i<4; ++i)
sum = sum +arr2D[arr2Mindex][i];
result[arr2Mindex]= sum;
}
}
public static void main(String[] args) {
job[] obj = new job[3];
for(int i=0; i<3; ++i){
obj[i]= new job(i);
obj[i].start();
try{
obj[i].join();
}catch (Exception e) {
e.printStackTrace();
}
}
String res="";
for( int j= 0; j<3; ++j)
res = result[j] + " ";
JOptionPane.showMessageDialog(null, res);
}
}现在我只得到54,这是二维数组的最后一个e,例如{12, 13, 14, 15}的正确答案。
当我检查以下行时:
obj[i]= new job(i); 通过传递如下的值
obj[i]= new job(0); 或
obj[i] = new job(1); 在上述两种情况下,我都得到了零。然而,当我键入:
obj[i] = new job(2);我拿到了54.
请有人指点我代码中的问题是什么。
发布于 2018-06-04 03:57:01
您正在覆盖结果值,而不是在循环中添加结果值。
变化
res = result[j] + " ";至
res = res + result[j] + " ";你就会得到所有的结果。
发布于 2018-06-04 04:12:50
错误是,您没有将其附加到现有的字符串中,而是替换它,因此只有最后一个值保留在末尾。就这样改变它,
for (int j = 0; j < 3; ++j)
res += result[j] + " ";https://stackoverflow.com/questions/50673124
复制相似问题