Waiting For a Thread to Complete


Thread t = new Thread(MyThread); t.start(); // do some other processing t.join(); // continues after thread t completes



It might be the case that you want one thread of execution to wait for another thread to complete before continuing with the current thread. Joining threads is a common method of causing one thread to wait for the completion of another thread. For example, in this phrase, we start thread t from within the thread that is executing these lines of code. We then, in most cases, do some additional processing and call the join() method on the thread object when we want to stop execution of this thread and wait for the thread t to complete. Once thread t completes, execution will continue to the statements following the line in which we called the join() method. If the thread t were already completed when we called join(), the join() method would return immediately.

An alternative form of the join() method is available that takes a long parameter containing a value in milliseconds. When this method is used, the calling thread will wait up to a maximum of that number of milliseconds before continuing, even if the thread on which the join() method is called has not completed. To be complete, there is also a third implementation of the join() method that takes two parameters, a long value in milliseconds, and an int value in nanoseconds. This method behaves exactly as the single parameter version, except that the millisecond and nanosecond values are added together to determine the length of time the calling thread should wait before continuing. This gives you finer grained control over the wait time.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net