• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

MULTI THREADING


Thread:
Thread is a flow of execution. In java language these Threads are classified into two types
1.Single Tasking(threading)
2.Multitasking(threading)

Single Tasking(threading)

Whenever processor executing only one task (operation) is known as single tasking. The main disadvantage with single tasking is utilization of processor time is not done properly to overcome this problem multi threading was introduced.
Multitasking(threading):
Whenever multiple tasks are executing simultaneously by the processor is known as multitasking. Multitasking is classified into two ways.
1.Process based Multi Tasking
2.Thread based Multi Tasking

Process based multi threading or multi tasking:
Whenever multiple processor of different applications are running simultaneously to perform different operation by the processor is known as process based multitasking.
Example:
playing game, playing audio song,loading website in a browser etc.. it can be simultaneous by the processor.

Thread based multithreading:
Whenever same part of program or multiple parts of programs are executing simultaneously known as thread based multi tasking.
OR
Whenever multiple threads are running simultaneously is known as multithreading. Thread is a flow of execution, in real time it can be treated as request from the end user. threads are mainly classified into two types.

1.Foreground thread
2.Background thread

Foreground thread:
If any thread is running in the foreground of java program is known as foreground thread. example: main method or main thread.

Background thread:
If any thread is running in the background of java program is known as background thread example: garbage collector.

Thread States:
New State:
If any thread is created without allocation of memory space then the thread is comes under the new state.
Ready State:
Whenever sufficient memory is allocated for the thread and if it is ready to execute then the thread under the ready state.
Running State:
Whenever a thread is under execution then that can be treated as running state.
Waiting state:
if any thread execution is stopped temporary is known as waiting state.
Dead state:
If any thread execution is stopped permanently then that is comes under the dead state.

NOTE:
Whenever thread is in either new or dead state no memory is available and it remaining three cases (ready, running, waiting) sufficient memory is allocated. In realtime multithreading can be used either to design server softwares or different gaming softwares etc….

Types of threads:
In java language threads are classified into two types.
1.Predefined thread
2.User defined thread
Predefined thread:
If any thread is already designed by sun microsystem known as predefined thread.
Example: main thread, garbage collector , etc…..

User defined thread: If any thread is designed by the user is known as user defined thread.
in java language threads can be classified in two different ways.
1.Using Thread classs
2.Using Runnable interface.

Key Points

Image






Thread classs

Rules to create a user defined thread :
1.Create a user defined class and extends thread class
2.Override run method of super class into user defined thread class.
3.Create an object (thread) for the user defined class.
4.Call run method with the help of start method.

Syntax:
classs Mythread extends Thread
{
    public void run()
    {
    --
    --
    }
    --
    --
}
public class Main
{
    public static void main(String args[])
    {
        Mythread objref=new Mythread();
        Objref.start()
    }
    
}



Write a java program to display message a 2sec time gap.

class Demo extends Thread
{
    public void run()
    {
        for(int i=0;i<=10;i++)
        {
            System.out.println("hello sateesh");
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException ie)
            {
                System.out.println(ie);
            }
        }
    }
}
public class Main
{
    public static void main(String args[])
    {
        Demo d=new Demo();
        d.start();
    }
}
                               

Output:
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello Sateesh

Runnable Interface

Runnable Interface:
Runnable is a predefined interface in java.lang package used to make a userdefined class thread class. Runnable interface is alternative approach to achieve multi thread in java application.
Rules to create a UDTC using runnable interface:
1.Create a user defined class and implements runnable interface.
2.Override run method with separate implementation .
3.Create a object for user defined thread class.
4.Create object for predefined thread class and attach user defined thread class.
5.Call the run method using predefined thread object with the help of start() method.

Syntax:
class UDTC implements Runnable
{
    public void run()
    {
        --
        --
    }
}
public class Main
{
    public static void main(String args[])
    {
        UDTC obj =new UDTC();
        Thread t=new Thread(obj);
        t.start();
    }
}



class Demo implements Runnable
{
    public void run()
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println("hello sateesh");
            try
            {
                Thread.sleep(3000);
            }
            catch(InterruptedException id)
            {
                System.out.println(id);
            }
        }
    }
}
public class Main
{
    public static void main(String args[])
    {
        Demo d=new Demo();
        Thread t=new Thread(d);
        t.start();
    }
}
                            

Output:
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello Sateesh
NOTE:
Even thread class also object can be attached if user defined thread class is derived from predefined thread class.
write a java program to achieve multithreading with respective to user defined thread.


class Cal extends Thread
{
    int x,y,z1,z2;
    void add()
    {
        x=20;
        y=30;
        z1=x+y
    }
    void sub()
    {
        x=30;
        y=40;
        z2=x-y;
    }
    public void run()
    {
        try
        {
            add();
            System.out.println("z1="+z1);
            Thread.sleep(3000);
            sub();
            System.out.println("z2="+z2);
        }
        catch(InterruptedException ie)
        {
            System.out.println(ie);
        }
       
    }
}
public class Main
{
    public static void main(String args[])
    {
        Cal c1=new Cal();
        c1.start();
        Cal c2=new Cal();
        c2.start();
        Cal c3=new Cal();
        c3.start();
    }
}
                              

Output:
z1=50
z1=50
z1=50
z2=-10
z2=-10
z2=-10

Thread class methods:

setName():
which can be used to set a user defined name for any thread.
UserdefinedThread objerf=new UserdefinedThread();
Objerf.setName("MyThread");
Program


getName():
which can be used to get the current thread name
System.out.prinln(obj.getName());
NOTE:
If no user defined name was given by default thread name will starts from thread-0, thread-1,………
Program
setPriority():
which can be used to set priority for a thread ,thread priority between 1 to 10.
1 Minimum priority
-------
-------
5 Normal priority
-------
-------
10 Maximum priority
The above three properties are existing on a predefined constant data members instead class shown below,
public static final int MIN_PRIORITY=1;
public static final int NORM_PRIORITY=5;
public static final int MAX_PRIORITY=10;
Syntax:
Obj.setPriority(any value between 1 to 10)
Obj.setPriority(Thread.MAX_PRIORITY)

Program
getPriority():
which can be used to get the current priority of thread.
Syntax:
System.out.println(obj.getPriority());
NOTE:
By default priority for any thread is 5 (normal priority).

Program
Sleep():
Which can be used to convert running state thread to waiting state .after specific time automatically thread with change from waiting to running state.
Syntax: public static final void sleep(milliseconds) throws InterruptedException
{
try
{
Thread .sleep(any integer value)
}
catch(InterruptedException ie)
{
--
}
}

Program
Suspend():
which is also can be used to change the running state into waiting state thread.
Obj.suspend();

Q:what is difference between the sleep() and suspend();
Sleep method can be convert running state thread to waiting state thread temporary some specific time .where as suspend method will convert running state to waiting state permanently.
Sleep method can be convert automatically waiting state to running state of thread ,once the given duration completed ,where as suspend method will never convert waiting state thread to another state automatically.

Program
Resume():
Which can be used to convert waiting state thread to ready state . resume method should be used after using suspend method.
Syntax:
Obj.resume();
Program

isAlive(): It is a Boolean method returns true if thread is an active state(ready or running or waiting ) and returns false another class (new or dead).
obj.isAlive();
Program

currnetThread():
which can be used to current execution thread information.
Syntax:
Thread.currentThread();
Which gives thread name, priority, group
NOTE:
Whenever multiple related threads are combine into a single group known as thread group.
Program

Join:
Which can be used to combine multiple threads
Syntax:
public final void join() throws InterruptedException
try
{
obj.join();
obj.join();
--
--
}
Program

run():
It is a predefined method of runnable interface overridden in the thread class empty body ,which contains logic to processes the thread or to run the thread.
Run method always should be overridden in our user defined thread class with separate business logic.

class user defined thread extends Thread
{
public void run()
{
--
--
}
Program

start():
Which can be used to start the execution of the thread by calling run method.
Obj.start();
Program

stop():

Which can be used to stop the execution of thread or which converts running thread to dead state.
Obj.stop();
Program

Key Points

Image
Thread Synchronization or thread safe:

If multiple threads are trying the same resource (working on same object) then there may be a chance of getting irreparable results ,to overcome this problem thread synchronization was introduced.
Definition: Restricting of a thread to with a resource if already that resource is utilize by another thread is known as thread synchronization or thread safe.
In java language thread synchronization can be achieved in two different ways

1.Using synchronized block.
2.Using synchronized method.

Using synchronized block:
This can be used to make a set of statements of method as synchronized.
Syntax:
synchronized(this)
{
--
--
}
In the above example synchronized is a keyword or access modifier in java language and (this) represents current executable thread.
The statements whatever written in synchronized block or executed by one thread at a time(until and unless compilation of first thread execution no other thread are allowed ,because at this time their may be a chance of irreliable result. Write a java program to achieve thread synchronization for the following scenario.
Here two passengers are trying to reserving same berth in the same time(available berths are only one).



Without synchronized

class Reserve implements Runnable
{
    int available=1;
    int wanted;
    Reserve (int i)
    {
        wanted=i
    }
    public void run()
    {
        System.out.println("avalable berts"+available);
        if(available>=wanted)
        {
            String name=Thread.currentThread().getName();
            System.out.println(wanted+"berts reserved for person"+name);
            try
            {
            Thread.sleep(2000);
            available=available-wanted;
            }
            catch(Exception e)
            {
            System.out.println(e);
            }
        }
        else
        {
            System.out.println("sorry ! no berths");
        }
    }
}
public class Main
{
    public static void main(String args[])
    {
        Reserve r=new Reserve(1);
        Thread t1=new Thread(r);
        Thread t2=new Thread(r);
        t1.start();
        t2.start();
    }
}                              

Output:
avalable berts 1
1 berts reserved for person Thread-0
avalable berts 1
1 berts reserved for person Thread-1
Using synchronized block



class Reserve implements Runnable
{
    int available=1;
    int wanted;
    Reserve (int i)
    {
        wanted=i;
    }
    public void run()
    {
        synchronized(this)
        {
            System.out.println("avalable berts"+available);
            if(available>=wanted)
            {
                String name=Thread.currentThread().getName();
                System.out.println(wanted+"berts reserved for person"+name);
                try
                {
                    Thread.sleep(2000);
                    available=available-wanted;
                }
                catch(Exception e)
                {
                    System.out.println(e);
                }
            }
            else
            {
                System.out.println("sorry ! no berths");
            }
        }
    }
}
public class Main
{
    public static void main(String args[])
    {
        Reserve r=new Reserve(1);
        Thread t1=new Thread(r);
        Thread t2=new Thread(r);
        t1.start();
        t2.start();
    }
}                              

Output:
avalable berts 1
1 berts reserved for person Thread-0
avalable berts 0
sorry ! no berths
Using synchronized Method



class Reserve implements Runnable
{
    int available=1;
    int wanted;
    Reserve (int i)
    {
        wanted=i;
    }
    synchronized public void run()
    {
        System.out.println("avalable berts"+available);
        if(available>=wanted)
        {
            String name=Thread.currentThread().getName();
            System.out.println(wanted+"berts reserved for person"+name);
            try
            {
                Thread.sleep(2000);
                available=available-wanted;
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
        else
        {
            System.out.println("sorry ! no berths");
        }
    }
}
public class Main
{
    public static void main(String args[])
    {
        Reserve r=new Reserve(1);
        Thread t1=new Thread(r);
        Thread t2=new Thread(r);
        t1.start();
        t2.start();
    }
}
                           

Output:
avalable berts 1
1 berts reserved for person Thread-0
avalable berts 0
sorry ! no berths