There are two threads in this program, the main thread(class Test) and the worker thread(class Job). Now when you say: thread.start(), the worker thread starts executing on a separate stack. The main thread continues to execute simultaneously. The main thread could reach the line: much earlier than the worker thread. So the situation can be this, that when the worker thread just starts, the main thread actually reaches the println statement and prints the value of the variable. To stop this, and to let the worker thread complete its task, we have the wait method, which puts the main thread on wait and lets the worker thread finish its task in the for loop. Then the main thread prints the value of the Integer variable which is 999999 since the worker thread has come out of the loop. I hope you understand. Please read K&B page 721 for more details.
Preparing for SCJP 6.0
Joined: Sep 09, 2008
But, I think the thread.wait(); means let the job thread wait, not the main thread.
You should be 100% certain that wait() is a method of Object.
Consider 2 threads: Thread A carries out a loooong task. Thread B must wait for A's result to go on with its job.
This trick between threads happens with a single object that both threads can access: a token. it's like the piece of wood that the athletes running 4x100m in the Olympics: Runner 1 starts, Runner 2 waits for the token from Runner 1, as soon as he gets it Runner 2 starts and so on...
Here's the first runner,
that holds a wooden stick.
This runner has a loooong task to do,
and then he will give the token to another runner.
Here's the second runner
that can also receive a wooden stick.
This second runner has also something to do,
but he'll have to wait for the token first.
Here's the complete code.
Conclusion: Using a single object, two threads may schedule in what order they will run in accuracy.
In the question you have posted, there two threads: Job and main. They schedule themselves based on the [B]thread[B] instance.
It's just a choice to use this instance instead of any other object.
Review: When thread A calls token.notify() it says: You may take the token. When thread B calls token.wait() it is waiting to take the token. Always synchronize on the token. [ September 15, 2008: Message edited by: Nikos Pugunias ]
But not to beat a dead horse I feel it is important for programmers to understand that the execution of the stick.notify() method does not let the waiting thread to run. A waiting thread will run when the synchronized block containing the notification is exited. A notify() method can be placed anywhere in the synchronized block.
Software development is an exercise in thinking not coding.
Originally posted by Ninad Kulkarni: can any one focus on it?
Generally, when you have a new question, you should start a new topic. It is not a good idea to hijack another poster's topic -- besides being against netiquette, it also don't generate many responses, as you see.