Ich habe folgenden Code:
Adder
RandomAdderRunable und main-Methode
Jetzt meine Frage, besteht da eine Gefahr, dass der Adder das falsche Ergebnis zurück gibt?
Java:
public class Adder{
public Adder(){}
public int add(int a, int b){
return a+b;
}
}
Java:
import java.util.Random;
/**
* Write a description of class RandomAdderRunable here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class RandomAdderRunable implements Runnable
{
private boolean isRunning;
private String name;
Random rand = new Random();
Adder ad;
public RandomAdderRunable(String name, Adder ad){
this.name=name;
this.ad=ad;
}
public void shutdown(){
if(isRunning){
isRunning=false;
System.out.println(name+" is clocking out.");
try{
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
}
public void run() {
isRunning=true;
while(isRunning){
int a=rand.nextInt(27);
int b=rand.nextInt(27);
int addResult=ad.add(a,b);
int localResult=a+b;
System.out.println(name+" Adder "+addResult+" : "+" Local: "+localResult);
if(!(addResult==localResult)){
System.out.println("Something is wrong in "+name+" bye.");
shutdown();
}
}
}
public static void main(String[] args) throws InterruptedException{
Main sleeper=new Main();
Adder ca=new Adder();
RandomAdderRunable r1=new RandomAdderRunable("A", ca);
RandomAdderRunable r2=new RandomAdderRunable("B", ca);
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
Thread.sleep(10000);
r1.shutdown();
r2.shutdown();
}
}
Jetzt meine Frage, besteht da eine Gefahr, dass der Adder das falsche Ergebnis zurück gibt?