Forums Register Login

A Question about Synchronized and Thread?

+Pie Number of slices to send: Send
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();
}
}
+Pie Number of slices to send: Send
This statement is the culprit:
System.out.println("radius= "+radius+" diameter/2= "+diameter/2);
Example 1.
Thread 1 executes
"radius= "+radius
Thread 2 calls setRadius and executes
this.radius = radius;
this.diameter= radius*2;
Thread 1 executes
+" diameter/2= "+diameter/2.
Example 2.
Thread 1 calls setRadius and executes
this.radius = radius;
Thread 2 executes
"radius= "+radius+" diameter/2= "+diameter/2
Thread 1 executes
this.diameter= radius*2;
Read access to the instance fields is not protected by synchronized code.
+Pie Number of slices to send: Send
also, just a general note, the variables radius and diameter should be made private, for proper encapsulation.
+Pie Number of slices to send: Send
Thanks a lot. I understand now.
[ March 05, 2003: Message edited by: My Twok ]
Getting married means "We're in love, so let's tell the police!" - and invite this tiny ad to the wedding:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 477 times.
Similar Threads
Quession about Pass value
Please help Doubt ?
Doubt on Mocktest
encapsulation-doubt
Encapsulation (was useless: Am i right!)
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 19, 2024 02:08:32.