线性规划中的消旋条件
附加的程序代码大部分时间会产生以下输出:
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语句是在单独的线程中执行的
或者是控制台。输出以一种奇怪的方式提示
我对这样的事情怎么会发生感到困惑,即使它很罕见
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();
}
}
# 1 楼答案
只有一个线程,因此代码中不能有竞争条件。您看到的是
System.out
和System.err
流的交错。参见示例Cause runtime exceptions to be properly ordered with println in console output# 2 楼答案
^{} 将消息打印到stderr(
System.err
),而所有其他输出都输出到stdout(System.out
)。默认情况下,两个standard output streams被重定向到同一目标(您的终端)。所以你的程序是决定性地运行的,它只是输出到两到两个通道这种行为其实是个好主意;程序可以重定向输出,但仍会向用户显示错误。但是,如果您不想要它,可以使用打印错误到标准输出