Implementing Threads in java

The thread is nothing but a single piece of program or process, for any program, there will be the main thread and some other threads. Implementing thread in java is a two steps process.

  1. First of all, we have to define a function which can be executed as a thread.
  2. Now, this function has to be executed as a thread.'

 

Explanation:

  • The signature of a functionality using which we implement a thread is defined in an interface by name ‘Runnable’. This interface has one function definition public void run () for which we need to provide body.
  • After providing body, we need to execute this functionality as a thread (i.e. simultaneously with other parts of the program).
  • There is a class by name Thread present in the API. This class supports much functionality which makes a given functionality to get executed as a thread. One such functionality is the start () method.
  • The start () method recognizes the run () method of Runnable interface and then the run () method is executed as a thread.
  • Thread class and Runnable interface are the two structures using which we implement Thread-based multitasking in java.

Examples:

Interface Runnable

{

Public void run ();

}

Class thread implements Runnable

{

Public void run ()

{

-----------------------

}

-------------------------------------------------------------------------------------------

}

Implement threads either of the following two ways:

Class A implements Runnable

{

Public void run ()

{

}

--------------------------------------------------------------------------------------------

}

Or

Class A extends Thread

{

Public void run ()

{

}

---------------------------------------------------------------------------------------------

}

  • Whether we extend thread class or implement the Runnable interface directly, we are using run () method of the runnable interface i.e. using Runnable interface directly or indirectly compulsory.
  • So by using Runnable interface, we can define threads in java.

 

Implementing Threads in JAVA Homework Help

Tutorspoint.com provides the best Help with Java Assignment, Java Programming Help &  java homework solutions at the affordable price with high-quality work.