As we all know, wait() method is implemented in Object instead of Thread. Then, how can we say "A thread that calls wait() releases the virtual CPU..." (quoted from RHE) Why don't we say "An object that calls wait() releases the virtual CPU?" Thanks, Jenny
Just remember, if code is being executed, it's being executed by some thread. That thread might be a thread you created or it might be the main thread that is created by the JVM. So, any call is really being performed by a thread, including a call to wait. In general, when we talk about time-slicing and giving up the processor, we're talking about threads, so it just makes more sense to put it into that context. I hope that answers your question, Corey
Another way of thinking about it that might reduce some confusion. People sometimes think that because there is a Thread() object 't' then 't' is somehow responsible for what gets executed. That really isn't correct. The Java object is just a convenient handle for us, the real true-blue computational thread is something very different and is happening deep in the JVM. That real thread is what is calling wait() on some Object, and hence releasing its lock on the very same Object. Objects don't have the virtual CPU, threads do. Objects don't have control of a lock on another Object, threads have the lock.
Reid - SCJP2 (April 2002)
Joined: Feb 01, 2002
If everything is running in threads, why do we need Thread class? What are the reasons to have multiple threads running in a program? Thanks, Jenny
Joined: Dec 20, 2001
The Thread class is really there so that we, as programmers have something substantial with which we can control threads. There are lots of situtations where you'll want to have multiple threads running. For instance, take a look at a word processor that has real-time spell checking (like MS Word). The spell checking is being done by a separate thread that runs in the background. Also, let's suppose you've written an application and part of that application requires a great deal of processing time. If you were to do this with just one thread, you might have a problem in that your app will become "unresponsive" for some time. In stead, you could create a separate thread that will do that work and another thread could continue to take input from the user. These are just a couple generic examples, but there are all sorts of reasons to use threads. The Thread class is just a means for us to use them effectively. I hope that helps, Corey