14.02. Creating threads by extending the thread class

Creating threads by extending the thread class

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial offers a basic introduction to multithreading. This tutorial shows the basic execution of the program with multiple threads. The threads that have several unique properties, such as parallel execution, are shown here.

In the following program, we Extend “Thread class”. Then override the public void run() method which will be executed when the thread is started.

In for loop, we write the logic (looping from 1 to 9 to display numbers from 1 to 9). To start the thread, we create an object of the above class.

Call the start()method on the object created.  Now thread will start its execution in parallel.

We can call the run() method instead of the start () method, but it would behave like a normal method. This method should be called by JVM. It specified that if we call run() method of these threads directly then the execution of all of them is being handled by the same current thread and no multithreading will take place.

Example:

Output:

In the following program, multithreading takes place and the output reflects simultaneous execution of threads.

When the execution method is called through the start () method, a new independent thread is assigned to execute the execution method, so if more than one thread calls the start method () it means that its execution method is run through separate threads.

Output:

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments