Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on thread

 
prajkta patil
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen if you attempt to compile and run the following code?
<code>
public class Master{
boolean bContinue=false;
public static void main(String argv[]){
Master m = new Master();
m.go();
}
public void go(){
Slave s = new Slave(this);
Thread t1 = new Thread(s);
t1.start();
while(bContinue==false){
}
s.setPrice(200);
}
}

class Slave implements Runnable{
int iPrice =100;
Master master;
Slave(Master m){
master=m;
}
synchronized public void setPrice(int iM){
iPrice=iM;
}

synchronized public void run(){
master.bContinue=true;
while(true){
System.out.println(iPrice);
}

}
}

</code>

answer is"Compilation and repeated output of 100"

can anybody explain me how it comes?

i think only one synchronised method (run())is accessed by thread.so that setprice can have acess.

& one more question can i write like"public synchronised void run()"?
 
Lahiru Abeydeera
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a relly bad Question. The author have assumed things that we can't guarantee.



sychronized void run() is perfectly legal as synchronized doesn't affect overriding.

Here the question author assumes that when you call the run method Thread(t1) gets the object lock and Master can't access the Slave s object until t1 releases it. But how can u guarantee that run() from t1 will get the lock before the main thread in Master class does.

So we cant guarantee the output. but that output in the answer is possible
and it will compile fine

If i'm wrong somebody please inform me


Lahiru Malinda
(SCJP 1.4 -95%)
[ January 17, 2005: Message edited by: Lahiru Abeydeera ]
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because go() does not get past "while(bContinue==false){}" until bContinue is set to true inside of Slave.run(), at which point slave.Run() already has the lock.

However, there is no formal guarantee that Slave.run() will get any CPU time. go() could just keep looping forever. In real life, there will be time slicing.

[ January 17, 2005: Message edited by: Mike Gershman ]
[ January 17, 2005: Message edited by: Mike Gershman ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic