File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A Question about Synchronized and Thread?

 
My Twok
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
 
Marlene Miller
Ranch Hand
Posts: 1392
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jasper Vader
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also, just a general note, the variables radius and diameter should be made private, for proper encapsulation.
 
My Twok
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot. I understand now.
[ March 05, 2003: Message edited by: My Twok ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic