Saturday, February 4, 2017

Muti Threading Java



Multi threading is the ability to handle multiple processes, i.e. performing different task in parallel.

A Single application running is a process and a process can have multiple threads. For an example Microsoft Word is an application and the spell checker can be considered as a thread.

When the main method is called a thread named main thread is created and executes the program.


Creating a Thread


Thread object can be created as shown below, and when the start ( ) method is called, the run ( ) method in the thread class is executed







Implementing Multithreading

The thread class can be extended and the run ( ) method can be overridden as shown below.













Note:

It is not a good practice to inherit the thread class just to override the run ( ) method, Therefore it is more suitable to implement the runnable interface. Therefore when creating thread objects we can pass the runnable object. When we pass the runnable object we tell the thread object where to find the run ( ) method.




Example Multithreading

In the below example two threads are created for a Hare and Tortoise, both threads are executed simultaneously, and the result set is produced accordingly.



Race.java


Above Class is a thread class and two instances of above class is created in the Multithreading class shown below, both threads are executed simultaneously and the winner is set to a Static variable in order to display which thread has won the race.


Multithreading.java




I won't be posting the results for this example because I don't want to ruin the fun part.You can check it out for yourself.

There  is much more to threads than what is mentioned here,Follow the link.

http://www.javatpoint.com/priority-of-a-thread

The Following Video will help understand the concept of threading more clearly.





No comments:

Post a Comment