17.3 Programming with Threads


17.3 Programming with Threads

Java and KJP provide to the programmer several ways to implement threads. The most relevant applications for threads are programming with GUI and animations. The Java Thread class allows you to create objects that have thread behavior. A thread can be started and run, can be paused and resumed, until it becomes null. The class includes the following methods: start(), run(), sleep(), join(), yield(), and so on.

The start() method starts the thread executing and invokes the run() method. The run() method contains the body of the code to be executed by the thread. When this method returns, the thread terminates.

A thread can be paused for a certain time period by calling the sleep() method. The statement sleep(50) means pause for 50 milliseconds. If you know your thread will be idling for an unspecified length of time, you may allow other threads with the same priority or greater priority (not lesser priority) to execute, by using method yield(). It is similar to the sleep() method, but without the specific time indication.

The join() method call waits synchronously for the thread to become inactive. This allows different threads a chance to coordinate their activities. For example, Thread A calls this method in Thread B that causes Thread A to block until Thread B has completed, and then Thread A can continue. When the thread is assigned with a null value, it stops at the current instruction.




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

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