Thread creation, in the context of Java, occurs either by extending the thread class or implementing the runnable interface.
In Java, an object of the thread class represents a thread. When a thread is first created, it must be permenantly bound to an object with a run() method; when invoked, it should invoke the object's run() method.
Implementing the runnable interface involves the following steps:
- A class implements the runnable interface and provides the run() method executed by the thread. An object that belongs to this class is a runnable object.
- The thread class object is created by passing the runnable object to the thread constructor.
- The start() method is invoked on the thread object created in the previous step.
- When the run() method ends, the thread also ends.
Extending the thread class involves the following steps:
- The java.lang.Thread class is extended by using extend.
- By overriding the run() method of the subclass extended from the thread class, the thread’s executed code is defined.
- An instance of this subclass is created.
- By invoking the start() method on this instance of the class, the thread runs.
The runnable interface is generally preferred over extending the thread class for two reasons:
- A subclass cannot extend another class when extending the thread class. However, when using the runnable interface, the subclass can extend another class.
- In some cases, the runnable interface is sufficient, as inheriting the whole class may lead to excessive overhead.
0 Comments