If by serial you mean you want the numbers to be in order, just running two threads like that doesn't have a defined outcome - the JVM manager, which decides which thread gets to run when, may share time more or less equally, or let one thread run all the way to completion before giving runtime to the second thread.
One way to do this might be to call "sleep()" in each thread if the current number it wants to print out it higher than the next expected number. Not sure why you would make two threads tag-team it like this, though...
Joined: Jan 30, 2006
Yes I mean they should be printed in order.
Using sleep() is just doesn't appear a right solution.[In fact I tried this one with sleep(2000) but it didn't output as iexpected]
My implementation depends upon wait/notify mechanism and toggling the flag(even).
So Once Counter lock is acquired there will be either call to nextOdd or nextEven. So I think my solution should work.
Kamal: Using sleep() is just doesn't appear a right solution.
Indeed it is not. Sleep does not guarantee any order. It just means that the calling thread will be suspended for the specified time. Whether the other thread takes over or not is totally left to chance. Wait-notify indeed is the way to go.
However, using a different lock for printing odd and even will give better control over the process. If you are on or above jdk 5 you can use the same lock and different conditions for priniting odd and even numbers. Let know if you want to know anything about this approach.
However, using a different lock for printing odd and even will give better control over the process.
Can you further explain it with some example? I mean in my case Counter object is maintaining count value as well and idea is just to switch between threads for printing alternatively. This approach may be naive but to me it was pretty straight forward.
If you are on or above jdk 5 you can use the same lock and different conditions for priniting odd and even numbers.
Again I will request for the code
I've just started with thread examples so I'm trying with basic blocks.
This is what i was talking about. (It is for jdk 5 and above but you can use the same idea in lower jdk versions also)
The benefit of using different conditions for odd and even printing is that you exactly know which thread you will be signalling. If you use the instance lock (synchronized keyword) then it may be a possibility that someone extends the class and adds one more synchronized method and starts waiting on the instance monitor. That will introduce subtle bugs in your code. The only idea of doing the above is to have a better control.
There is an alternative way of doing this by using Exchanger I am sure you will get an idea on how to use that by seeing its javadoc.