Define and instantiate a thread in one of two ways:
¦ Extend the java.lang.Thread class.
¦ Implement the Runnable interface.
Extending java.lang.Thread
The simplest way to define code to run in a separate thread is to
¦ Extend the java.lang.Thread class.
¦ Override the run() method.
Keep in mind that you're free to overload the run() method in your Thread
subclass:
But know this: The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, and it will execute this method for you in a separate call stack after the thread has been started. With a run(String s) method, the Thread gisclass won't call the method for you, and even if you call the method directly yourself, execution won't happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.
Instantiating a Thread:
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
The Thread class itself implements Runnable. (After all, it has a run() method that we were overriding.) This means that you could pass a Thread to another Thread’s constructor:
Thread t = new Thread(new MyThread());
This is a bit silly, but it’s legal. In this case, you really just need a Runnnable, and creating a whole other Thread is overkill.
When a thread has been instantiated but not started (in other words, the start() method has not been invoked on the Thread instance), the thread is said to be in the new state. At this stage, the thread is not yet considered to be alive. Once the start() method is called, the thread is considered to be alive (even though the run() method may not have actually started executing yet). A thread is considered dead (no longer alive) after the run() method completes. The isAlive() method is the best way to determine if a thread has been started but has not yet completed its run() method.
No comments:
Post a Comment