File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question on thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question on thread " Watch "question on thread " New topic

question on thread

prajkta patil
Ranch Hand

Joined: Nov 13, 2004
Posts: 49
What will happen if you attempt to compile and run the following code?
public class Master{
boolean bContinue=false;
public static void main(String argv[]){
Master m = new Master();
public void go(){
Slave s = new Slave(this);
Thread t1 = new Thread(s);

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

synchronized public void run(){



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 that setprice can have acess.

& one more question can i write like"public synchronised void run()"?
Lahiru Abeydeera
Ranch Hand

Joined: Nov 05, 2004
Posts: 44
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

Joined: Mar 13, 2004
Posts: 1272
Because go() does not get past "while(bContinue==false){}" until bContinue is set to true inside of, at which point slave.Run() already has the lock.

However, there is no formal guarantee that 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 ]

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: question on thread
It's not a secret anymore!