附加的程序代码在大多数情况下产生以下输出:
6.0
8.0
10.0
12.0
java.lang.RuntimeException: dimensions not matching
at hausaufgaben.linearAlgebra1.VectorRn.add(VectorRn.java:41)
at hausaufgaben.linearAlgebra1.VectorRn.main(VectorRn.java:19)
3.0
6.0
9.0
12.0
但是在第二次执行时它产生了输出
6.0
8.0
10.0
12.0
java.lang.RuntimeException: dimensions not matching
3.0
6.0
9.0
12.0
at hausaufgaben.linearAlgebra1.VectorRn.add(VectorRn.java:41)
at hausaufgaben.linearAlgebra1.VectorRn.main(VectorRn.java:19)
这是否意味着在具有consoleoutput的简单程序中,已经存在在99.99%的时间内具有确定性行为的竞争条件?
或者是在一个单独的线程中执行的catch语句吗?
或者是控制台.output以奇怪的方式提出?
我对这样的事情发生了很困惑,即使很少见。
package hausaufgaben.linearAlgebra1;
public class VectorRn {
/**
* values that are the components
*/
private double[] values;
/**
* @param args
*/
public static void main(String[] args) {
VectorRn a = new VectorRn(1,2,3,4);
VectorRn b = new VectorRn(5,6,7,8);
VectorRn c = new VectorRn(1,2);
double d = 3;
System.out.println(a.add(b).toString());
try {
System.out.println(a.add(c).toString());
}catch(Exception e) {
e.getMessage();
e.printStackTrace();
}
System.out.println("\n"+a.mult(d).toString());
}
/**
* @param values copies the values passed to the constructor
*/
public VectorRn(double... values) {
this.values = new double[values.length];
System.arraycopy(values, 0, this.values, 0, values.length);
}
/**
* @param v2 the vector added to a clone of this object
* @return the sum of this Vector and v2
*/
public VectorRn add(VectorRn v2) {
if(this.values.length != v2.values.length)
throw new RuntimeException("dimensions not matching");
VectorRn modifiedClone = new VectorRn(this.values);
for(int i = 0; i < modifiedClone.values.length; i++){
modifiedClone.values[i] += v2.values[i];
}
return modifiedClone;
}
/**
* @param d the scalar by which the clone of this object will be multiplied
* @return the d'th multiple of this Vector
*/
public VectorRn mult(double d) {
VectorRn modifiedClone = new VectorRn(this.values);
for(int i = 0; i < this.values.length; i++) {
modifiedClone.values[i] *= d;
}
return modifiedClone;
}
/**
* @return a string that contains a list of the components of the vector separated by newline characters
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder tmp = new StringBuilder();
for(double d : values) {
tmp.append(d);
tmp.append("\n");
}
return tmp.toString();
}
}
答案 0 :(得分:5)
e.printStackTrace
将消息输出到stderr(System.err
),而所有其他输出则输出到stdout(System.out
)。默认情况下,standard output streams都会重定向到同一目标(您的终端)。因此,您的程序确定性地运行,它只是输出到两个通道。
这种行为实际上是一个好主意;程序可以重定向输出但仍然向用户显示错误。如果您不想要它,可以使用
将错误打印到stdoute.printStackTrace(System.out)
答案 1 :(得分:1)
只有一个主题,因此您的代码中不会出现竞争条件。您看到的是System.out
和System.err
流的交错。请参阅示例Cause runtime exceptions to be properly ordered with println in console output