Defining Multiple Threads

 

We define a thread using

run

() method of the runnable interface. A class can have only one run () method. Therefore, to define multiple threads, we need to define those many classes with

run

() methods for those many threads we want to define and implement.

 

Example program:

Class thread A extends Thread

{

Public void run ()

{

For ( int I =100;i<140; i++)

System. Out. Prinln(“ run of thread A:” +i);

System. Out. Prinln(“ end of thread A”);

}

}

Class thread B extends Thread

{

Public void run ()

{

For ( int I =400;i<43+; i++)

System. Out. Prinln(“ run of thread B:” +i);

System. Out. Prinln(“ end of thread B”);

}

}

Class thread C extends Thread

{

Public void run ()

{

For ( int I =4;i<40+; i++)

System. Out. Prinln(“ run of thread C:” +i);

System. Out. Prinln(“ end of thread C”);

}

}

Class Thread Test

{

Public static void main (string args [ ])

{

Thread A ta = new ThreadA ();

Thread A ta = new ThreadB ();

Thread A ta = new ThreadC ();

ta. Start ();

tb. Start ();

tc. Start ();

For ( int j =0;i<40+; j++)

System. Out. Prinln(“ Inside main :” +j);

System. Out. Prinln(“ end of main”);

}

}

 

Explanation:

  • The output of the above program cannot be guessed in the advance because, once the start () method hands over the run () method of the corresponding object to the local OS, it is up to the local OS to schedule them. This is why the output cannot guess.
  • In the above example, we have defined and implemented multiple threads by extending the Thread clas.
  • When our class is extending a class other than Thread class, then we define and implement Threads by implementing the runnable interface to our classes.

 

Multiple Threads Homework Help