HI: I have an application that runs 2 threads. I am trying to them using or not using "yield" from the command line. My output shows Thread1 and then Thread2 1-15 in that order. I thought they should be interspersed somewhat. At least thats they way it appeared on a Win98 PC and I have Win ME PC. Does the code look right?? Thanks
I think perhaps you are imagining that it is possible to have closer control over individual threads than is actually the case. In practise, when a number of threads are runnable, which one actually gets CPU at a particular instant is not under your control. It varies depending on which JVM you have and whether you use "green" or "native" threads. The yield() method just "suggests" to the JVM that it might like to stop giving CPU to the current thread and might like to give CPU to another runnable thread, if there is one. If you want to stop execution of a thread until a condition is met, you can use wait()/notify(). You can also interrupt() a thread, which will set its interrupted flag or, if it's waiting already, will cause the method that's waiting to throw InterruptedException. You can "suggest" to the JVM which threads are more important, using priorities. That's all you can do, pretty much. The useful-sounding stop(), suspend(), resume() etc. methods are not to be used, because they are deprecated due to deadlock risk. Threads are hard. One needs a good book (I have O'Reilly Java Threads, but there are others), or a lot of time to experiment, or both.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Joined: Dec 07, 2000
I am looking to see what happens to a thread if yield is called.
Hi Capp Should you not also be setting the yield flag before starting the 2 threads? If you start the threads, then figure out if the user wants to use yield or not and set the flag, the first thread will execute exclusively on a pre-emptive system until it figures out that the yield flag has been set to true. This is one possible explanation for the behaviour you are seeing. In any case, without yielding, whether or not there is any interleaving will depend on the underlying OS and whether or not it is time-sliced. On my system (Win98) there is interleaving even without yield, but of course the yield print messages are never output. If you want to know what happens when calling yield on different systems, your code should give you some idea, I would just suggest setting the flag before starting the threads, and possibly having more iterations in the run loop. Hope this helps Michael ------------------ "One good thing about music - when it hits, you feel no pain" Bob Marley
"One good thing about music - when it hits, you feel no pain" <P>Bob Marley