You can define and instantiate a thread in one of two ways:
■ Extend the java.lang.Thread class.
■ Implement the Runnable interface.
You should design a class that implements the Runnable interface, which also leaves your
class free to extend some other class.
To define a thread, you need a place to put your run() method, and as we just
discussed, you can do that by extending the Thread class or by implementing 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.
class MyThread extends Thread {
public void run() {
System.out.println("Important job running in MyThread");
}}
The limitation with this approach (besides being a poor design choice in most
cases) is that if you extend Thread, you can't extend anything else.
Implementing java.lang.Runnable
Implementing the Runnable interface gives you a way to extend any class you like,
but still define behavior that will be run by a separate thread. It looks like this:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
}}
Key points:
❑ Threads can be created by extending Thread and overriding the
public void run() method.
❑ Thread objects can also be created by calling the Thread constructor that
takes a Runnable argument. The Runnable object is said to be the target of
the thread.
❑ You can call start() on a Thread object only once. If start() is called
more than once on a Thread object, it will throw a RuntimeException.
❑ It is legal to create many Thread objects using the same Runnable object as
the target.
❑ When a Thread object is created, it does not become a thread of execution
until its start() method is invoked. When a Thread object exists but hasn't
been started, it is in the new state and is not considered alive
❑ Once a new thread is started, it will always enter the runnable state.
❑ There is no guarantee that the order in which threads were started
determines the order in which they'll run.
❑ A running thread may enter a blocked/waiting state because it can't acquire
the lock for a synchronized block of code.
❑ When the sleep or wait is over, or an object's lock becomes available, the
thread can only reenter the runnable state. It will go directly from waiting to
running
❑ A dead thread cannot be started again.
No comments:
Post a Comment