Hi there,
When I studied Synchronized and Thread today, I got a question. The following is my code, with which I supposed to get equaled radius and diameter/2 output to the console. But when I checked the result, there always had about 40 cases out of 100000 that the radius and diameter/2 were not equal. I did add synchronized modifier in front of the setRadius function. then why there still are such cases?
I appreciate your help!
public class Mycircle implements Runnable{
public double radius;
public double diameter;
public synchronized void setRadius(double radius) {
this.radius = radius;
this.diameter= radius*2;
}
public void run(){
for(int i=1;i<=100000;i++){
setRadius(i);
System.out.println("radius= "+radius+" diameter/2= "+diameter/2);
}
}
public double getRadius() {
return radius;
}
public static void main(String[] args){
Mycircle m=new Mycircle();
new Thread(m).start();
new Thread(m).start();
}
}
When I studied Synchronized and Thread today, I got a question. The following is my code, with which I supposed to get equaled radius and diameter/2 output to the console. But when I checked the result, there always had about 40 cases out of 100000 that the radius and diameter/2 were not equal. I did add synchronized modifier in front of the setRadius function. then why there still are such cases?
I appreciate your help!
public class Mycircle implements Runnable{
public double radius;
public double diameter;
public synchronized void setRadius(double radius) {
this.radius = radius;
this.diameter= radius*2;
}
public void run(){
for(int i=1;i<=100000;i++){
setRadius(i);
System.out.println("radius= "+radius+" diameter/2= "+diameter/2);
}
}
public double getRadius() {
return radius;
}
public static void main(String[] args){
Mycircle m=new Mycircle();
new Thread(m).start();
new Thread(m).start();
}
}