Extending the class Thread-Java

Definition

Defines the class that extends thread class and overrifes its code() method in the subclass. Each thread is separate instance of the class.

In the above programs contains two classes : ThreadY and ThreadX. Let us first consider the class ThreadX. The class ThreadX is derived from the class Thread. Thec class Thread contains one method-. Another class Thread Y is defined from the class Thread. The class ThreadY contains one method -run() method.


Example 1:



Output :


  I'm thread and running...

Example 2:

First Thread.java



Second Thread.java



Main Class which starts the “First Thread” and “Second Thread”



Output :

Message from Second Thread : 1
Message from First Thread : 1
Message from Second Thread : 2
Message from First Thread : 2
Message from Second Thread : 3
Message from First Thread : 3
Message from Second Thread : 4
Message from First Thread : 4
Message from Second Thread : 5
Message from First Thread : 5