![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e92. Creating a ThreadWhen a thread is created, it must be permanently bound to an object with arun() 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 // 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();
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
© 2002 Addison-Wesley. |