Monday, February 12, 2018

[Basics] Multithreading in java

Multithreading is a concept in java where we basically create more than one thread in program so that we can achieve the improved performance of the program.

How to Use Volatile keyword In Java

What is Process ?
Process is an instance of computer program that is being executing.
What is thread ?
Thread is the single unit of work or we can say a lightest process of computer program .

Thread is the simplest piece of process.

Multithreading in java 
            In Java by default the main thread is always run , if we cant to achieve the concurrency in programming we use the concept of multithreading.
Example – If we have a queue and we want to add the values in Queue and remove the value in a way that there should never be a List full situation occur of underflow situation occurred.To solve this problem we can use multithreading in java , where one thread is responsible for produce the number and push it in list and other thread is removing the number in list.

Thread Lifecycle-

Ways to create Thread in java
There are 2 ways to create threads in java
  • ·         By Extending Thread Class
  •        By Implementing Runnable Interface.

Program to create the Thread By Extending Thread Class

Explanation :

In Above Program
  • There are 2 classes one is main class and other is thread class.
  • MyThread class is a thread class where we are extending the Thread Class and over rite the  run() method of the class 
    • run() is the method we we need to write the logic we want to run while the thread will run. This is the most important method and all the code logic for thread need to write here only.
    • When we call the start() method it implicitly call the run() of the Thread class
  • In Run Method I have written the for we I am printing the current value along with the thread name.
  • The Main Class ThreadDemo , I have created 2 object of MyThread Class and We are calling start() method(which will start the thread).

NOTE: If I will directly call the run() method of the class , It will start my Main Thread only not the MyThread Class Thread.

By Implementing Runnable Interface.
In this way , we need to implement the runnable interface in our class and override the run() interface
The Only difference here is that we need to pass the runnable interface in construction while creating thread .
Thread t = new Thread(new MyRunnable());

Program of Runnable Interface 

In Above Program:
We are doing everything same as for thread class Only Thing we have changed is We need to Pass the Runnable Class in my Thread Class.

    Thread t = new Thread(new MyThread1());

Above is the Only Change. 

In Next Tutorial we will see how to Use Syncronization in Thread and when we need to use extend way and when runnable we will see in next tutorials.

In you have any Issue leave us a message . Will be happy to help

Thanks for reading



Post a Comment