This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Simple Thread Program : Need Clarification Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Simple Thread Program : Need Clarification" Watch "Simple Thread Program : Need Clarification" New topic
Author

Simple Thread Program : Need Clarification

Sumeet Chakraborty
Ranch Hand

Joined: Feb 05, 2009
Posts: 45
I was solving the mock test of Threads (SCJP 1.6) from the site : www.nikojava.wordpress.com (Q. No 65)

I came across the following question which seems simple to to me, but the output is something unexpected. Just have a look :

class Job extends Thread {
private Integer number = 0;
public void run() {
for (int i = 1; i < 1000000; i++) {
number++;
}
}
public Integer getNumber() {
return number;
}
}
public class Test {
public static void main(String[] args) {
Job thread = new Job();
thread.start();
System.out.println(thread.getNumber());
}
}

What is the output ?

1. It prints 0.
2. It prints 999999.
3. The output is not guaranteed to be any of the above.


My initial thought was it will print 999999 . But when I executed the code ... it printed 0. The answeron the site says its No 3 ( The output is not guaranteed to be any of the above).

After the call to start() the run() is invoked and thats where the loop modifies the number var. But still it didnt increment the value when executed.

This may be a simple one but I am sure I must missing a simple trick here . Could anyone please help me out ?

Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
The problem is that the main thread is not waiting for the other thread to finish, so when it prints the value the other thread might not have added anything. Try to add this: thread.join() just before you print the value. I think the result will be what you would expect.


All code in my posts, unless a source is explicitly mentioned, is my own.
Dawn Charangat
Ranch Hand

Joined: Apr 26, 2007
Posts: 249
The answer infact is option 3.

The thread executes independent of the parent, once it is started. Hence when the parent queries for the current status of variable "number", the thread will just return you the current status... it could be 0 [if the thread hasnt infact started execution], or 999999 [if the thread had completed the loop] or any number between 0 and 999999 [current status]. In your case, you got it as zero.... but then tell you what, you try executing that program for, say 10 times.... and you'll see that you will be getting a different output sometime during the course...
Sumeet Chakraborty
Ranch Hand

Joined: Feb 05, 2009
Posts: 45
Thanks all of you for your prompt reply . Its very much clear to me now. The bottom line is :

The main thread (or any other) runs independently without caring about the other running threads. And thats why join() method is in existance . right ??

Thanks again
Sumeet Chakraborty
Ranch Hand

Joined: Feb 05, 2009
Posts: 45
But what about this ???

class Job extends Thread {
private Integer number = 0;
public void run() {
for (int i = 1; i < 1000000; i++) {
number++;
}
}
public Integer getNumber() {
return number;
}
}
public class Test {
public static void main(String[] args)
throws InterruptedException {
Job thread = new Job();
thread.start();
synchronized (thread) {
thread.wait();
}
System.out.println(thread.getNumber());
}
}


I am calling wait from synchronized context which allows the other thread to complete its calculations in the run method. But a noify() is not called from anywhere . So how come the main thread reaches System.out.println(thread.getNumber());

??

According to me it should be in waiting pool state till a notify() is not encountered. right ???

The concrete output says it will print 99999.

Please clarify.
sebastian tortschanoff
Ranch Hand

Joined: Mar 19, 2009
Posts: 68
The main thread gets a lock on the Job-class.
Wait means: "Hey Thread! Stay in Pool, while main-Thread executes and finish (and subsequently releases the lock)."

Then, any other thread, pointed by the Scheduler, will be selected from the pool. In this case, a thread ,using the same Object (in synchronized context -means getting a lock).

When this thread calls the method thread.getNumber() (yet the same Object and it's state, too), the number printed will be 999999, no matter how long the other thread is waiting.


Yo've said:

According to me it should be in waiting pool state till a notify() is not encountered. right ???


Thats wrong. When one thread gets a lock and is put into wait, it does not release its lock.
When this thread is dead or notified, the lock is released. Notify can not provide information which waiting thread will be selected next by the scheduler.


Power from within.

Failed SCJP 2 times :-(
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

Sumeet this type of thing has been asked many times here. See this thread for details.

Also please use code tags when you post a source code...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Sumeet Chakraborty
Ranch Hand

Joined: Feb 05, 2009
Posts: 45
Thanks Ankit and Sebastian I think i got the reply i wanted.

And yes Ankit ... i didnt see that particular thread before, but it helped too. And from next time i will surely use code tags.

Thanks again
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Simple Thread Program : Need Clarification
 
Similar Threads
Thread Prog...
notify() question from Nikos
Thread-doubt on wait
a Thread Question from Nikos Blog
Threads -Niko-Blog Question 66