SCJP Chapter 9

Page 7

CertPrs8/Java 5 Cert. Study Guide/Sierra-Bates/225360-6/Chapter 9

Instantiating Threads (Exam Objective 4.1)

679

If you extended the Thread class, instantiation is dead simple (we'll look at some additional overloaded constructors in a moment): MyThread t = new MyThread()

If you implement Runnable, instantiation is only slightly less simple. To have code run by a separate thread, you still need a Thread instance. But rather than combining both the thread and the job (the code in the run()method) into one class, you've split it into two classes—the Thread class for the thread-specific code and your Runnable implementation class for your job-that-should-be-run-by-athread code. (Another common way to think about this is that the Thread is the "worker," and the Runnable is the "job" to be done.) First, you instantiate your Runnable class: MyRunnable r = new MyRunnable();

Next, you get yourself an instance of java.lang.Thread (somebody has to run your job…), and you give it your job! Thread t = new Thread(r);

// Pass your Runnable to the Thread

If you create a thread using the no-arg constructor, the thread will call its own run() method when it's time to start working. That's exactly what you want when you extend Thread, but when you use Runnable, you need to tell the new thread to use your run()method rather than its own. The Runnable you pass to the Thread constructor is called the target or the target Runnable. You can pass a single Runnable instance to multiple Thread objects, so that the same Runnable becomes the target of multiple threads, as follows: public class TestThreads { public static void main (String [] args) { MyRunnable r = new MyRunnable(); Thread foo = new Thread(r); Thread bar = new Thread(r); Thread bat = new Thread(r); } }

Giving the same target to multiple threads means that several threads of execution will be running the very same job (and that the same job will be done multiple times).

ch9-1128f.indd 679

11/28/05 12:16:49 PM


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.