Java Reference
In-Depth Information
Thread lifecycle methods
I should mention a few other methods briefly, starting with the Thread constructors:
Thread() , Thread("Thread Name") , and Thread(Runnable) . The no-argument and name-
argument constructors are used only when subclassing. But what's in a name? Well, by de-
fault, a thread's name is composed of the class name and a number such as a sequence num-
ber or the object's hashcode; on the standard JDK it uses sequence numbers, such as
Thread-0 , Thread-1 , and so on. These names are not very descriptive when you need to
look at them in a debugger, so assigning names like “Clock Ticker Thread” or “Background
Save Thread” will make your life easier when (not if) you wind up having to debug your
threaded application. Because of this, getName() / setName(String) methods return or
change the thread's name, respectively.
We've seen already that the start() method begins the process of assigning CPU time to a
thread, resulting in its run() method being called. The corresponding stop( ) method is de-
precated; see Stopping a Thread , where I also discuss interrupt() , which interrupts
whatever the thread is doing. The method boolean isAlive() returns true if the thread has
neither finished nor been terminated by a call to its stop() method. Also deprecated are
suspend() / resume() , which pause and continue a thread; they are prone to corruption and
deadlocking, so they should not be used. If you've created multiple threads, you can join()
a thread to wait for it to finish; see Rendezvous and Timeouts .
The methods int getPriority() / void setPriority(int) show and set the priority of a
thread; higher priority threads get first chance at the CPU. Finally, wait() / notify() / noti-
fyAll() allow you to implement classical semaphore handling for such paradigms as produ-
cer/consumer relationships. See the javadoc page for the Thread class for information on a
few other methods.
Each of these techniques will get you started, but they tend not to scale well. For any volume
work, use of a thread pool is considered essential. Thread pools are provided by the Execut-
ors class, as described in Simplifying Synchronization with Locks .
Displaying a Moving Image with Animation
Problem
You need to update a graphical display while other parts of the program are running.
Search WWH ::




Custom Search