The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.lang  [58 examples] > Threads  [11 examples]

e92. Creating a Thread

When a thread is created, it must be permanently bound to an object with a run() method. When the thread is started, it will invoke the object's run() method. More specifically, the object must implement the Runnable interface.

There are two ways to create a thread. The first is to declare a class that extends Thread. When the class is instantiated, the thread and object are created together and the object is automatically bound to the thread. By calling the object's start() method, the thread is started and immediately calls the object's run() method. Here is some code to demonstrate this method.

    // This class extends Thread
    class BasicThread1 extends Thread {
        // This method is called when the thread runs
        public void run() {
        }
    }
    // Create and start the thread
    Thread thread = new BasicThread1();
    thread.start();
The second way is to create the thread and supply it an object with a run() method. This object will be permanently associated with the thread. The object's run() method will be invoked when the thread is started. This method of thread creation is useful if you want many threads sharing an object. Here is an example that creates a Runnable object and then creates a thread with the object.
    class BasicThread2 implements Runnable {
        // This method is called when the thread runs
        public void run() {
        }
    }
    // Create the object with the run() method
    Runnable runnable = new BasicThread2();
    
    // Create the thread supplying it with the runnable object
    Thread thread = new Thread(runnable);
    
    // Start the thread
    thread.start();

 Related Examples
e93. Stopping a Thread
e94. Determining When a Thread Has Finished
e95. Pausing the Current Thread
e96. Pausing a Thread
e97. Determining If the Current Thread Is Holding a Synchronized Lock
e98. Allowing an Application with Live Threads to Exit
e99. Listing All Running Threads
e100. Using a Thread-Local Variable
e101. Getting the Stack Trace of an Exception
e102. Implementing a Work Queue

See also: Arrays    Assertions    Classes    Commands    Numbers    Objects    Strings    System Properties   


© 2002 Addison-Wesley.