Sunday, September 4, 2016

JAVA MULTITHREADING: Creating and starting Threads

There are altogether 3 ways to create a thread. They are as follows:
  1. By extending Thread class
  2. By implementing Runnable interface
  3. By using an anonymous class of Runnable interface type


FIRST METHOD:
As can be seen from the picture, the App class consists of a main method. 

Apart from that, it has a separate internal class called Runner which extends Thread class.

Here, it has been chosen to override the run() method of the Thread class, to do something custom for us. After printing the string, the thread sleeps for 100 milliseconds.

Inside the main() method, we have two new instances of Runner class type. Both of these invoke their start() method.


It is important to notice that start() method has been called and not the run() method defined earlier. 

This is to avoid running the method on the application’s main thread. 

Calling start() method makes sure that the runner1 object runs on a separate new thread.

The output of the above programs looks like this:






SECOND METHOD:
The body of the App class remains almost the same.

The only difference this time is that the internal class Runner IMPLEMENTS the Runnable method instead of the inheritance as in the previous case.

Here, it becomes mandatory to implement the run() method of Runnable interface.

Inside main(), two new objects get created of Thread class type AND a new Runner object is passed as parameter inside the constructor of the Thread class.



The output remains the same.



THIRD METHOD:  This probably is the best method, as it doesn't require an extra internal class definition.
This method uses anonymous class to create a new Thread.


Here, a new Thread object has been created and a Runnable type object has been passed inside t1's constructor after defining the run() method.

This is a derivation of the second method.

No comments:

Post a Comment