permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A Question about Synchronized and Thread? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A Question about Synchronized and Thread?" Watch "A Question about Synchronized and Thread?" New topic
Author

A Question about Synchronized and Thread?

My Twok
Greenhorn

Joined: Mar 05, 2003
Posts: 2
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();
}
}


SCJP, SCWCD
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
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

Joined: Jun 10, 2002
Posts: 57
also, just a general note, the variables radius and diameter should be made private, for proper encapsulation.


giddee up
My Twok
Greenhorn

Joined: Mar 05, 2003
Posts: 2
Thanks a lot. I understand now.
[ March 05, 2003: Message edited by: My Twok ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A Question about Synchronized and Thread?