Instantiating a Thread:

Every thread of execution begins as an instance of class Thread. Regardless of whether your run() method is in a Thread subclass or a Runnable
implementation class, you still need a Thread object to do the work.
If you extended the Thread class, instantiation is simple
MyThread t = new MyThread()
If you implement Runnable
To have code run by a separate thread, you still need a Thread instance.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
r- it is known as runnable target
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.
You can pass a single Runnable instance to multiple Thread objects,
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).

No comments:

Post a Comment