. .
Chapter 4. Lifecycle
Thread Lifecycle
APIs Used in This Chapter
The Class java.lang.Thread
The Class Extensions.InterruptibleThread
The Interface java.lang.Runnable
In which the reader is treated to a comprehensive explanation of the intricacies in the life of a
thread--birth, life, and death-- even death by vile cancellation. A small program that illustrates
all these stages concludes the chapter.
Thread Lifecycle
The fundamental paradigm of threads is the same in all the libraries. In each, the program starts up
in the same fashion as single-threaded programs always have--loading the program, linking in the
dynamic libraries, running any initialization sections, and finally, starting a single thread running
main() (the main thread). The main function will then be free to create additional threads as the
programmer sees fit (Code Examples 4-1 to 4-3).
In Pthreads and Win32, you call the create function with a function to run and an argument for the
function to run on. Java follows the same paradigm, but the API is rather distinct. In Java you
subclass Thread, defining a run() method for it, then instantiate an instance of it and call
start(). You can see how this maps directly onto the POSIX model. It is important to
distinguish between the thread object that you've just created with new Thread and the thread as
we've described it, which is created in the start() method.
Example 4-1 Simple Call to Create and Exit a POSIX Thread
error = pthread_create(&tid, NULL, start_fn, arg);
void *start_fn(void *arg) {
Example 4-2 Simple Call to Create and Exit a Java Thread
Public class MyThread extends Thread {
public void run() {
Thread t = new MyThread();
Example 4-3 Simple Call to Create and Exit a Win32 Thread
handle = CreateThread(NULL, NULL, start_fn, arg, NULL, &tid);
void *start_fn(void *arg) {
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks