How to make Thread by extending Thread class

Points To Remember
  • We can implement Runnable interface or extend Thread class to create threads.
  • We have to override the run() method to define the functionality of thread.
  • We should call start() method to start execution of a thread as a new entity, if we call run() method on a thread then it will not start a new thread.
  • We cannot guarantee which thread will execute first even if we prioritize the threads.
  • A thread whose run() method is executed completely reaches the dead state and cannot be invoked again.
Program : Making 3 Threads using Thread Class
In the following example we are making three different threads in the class Test which extends the Thread class. We just pass a parameter name to each object of Test thread to distinguish between them.
class Test extends Thread{

  String name;

  public Test(String name){
    this.name = name;
  }

  public static void main(String args[]){  
    System.out.println("main started");

    Thread t1 = new Thread(new Test("Thread t1"));
    Thread t2 = new Thread(new Test("Thread t2"));
    Thread t3 = new Thread(new Test("Thread t3"));
    t1.start();
    t2.start();
    t3.start();

    System.out.println("main ended");

  }

  @Override
  public void run(){
    System.out.println(name);
  }

}
Running the program for the first time.
main started
Thread t1
Thread t3
Thread t2
main ended
Running the program for the second time.
main started
main ended
Thread t2
Thread t1
Thread t3
Running the program for the third time.
main started
main ended
Thread t1
Thread t3
Thread t2
The above outputs confirms that we cannot guarantee the execution of any thread. Any thread may execute first.

No comments:

Powered by Blogger.