Latest update

6/recent/ticker-posts

Thread Creation

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:

  1. 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.
  2. The thread class object is created by passing the runnable object to the thread constructor.
  3. The start() method is invoked on the thread object created in the previous step.
  4. When the run() method ends, the thread also ends.

Extending the thread class involves the following steps:

  1. The java.lang.Thread class is extended by using extend.
  2. By overriding the run() method of the subclass extended from the thread class, the thread’s executed code is defined.
  3. An instance of this subclass is created.
  4. 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.

Post a Comment

0 Comments