MULTI 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:

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

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.

Rules to create a user defined thread :

  1. Create a user defined class and extends thread class or implements runnable interface.
  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()
{
--
--
}
--
--
}

Mythread objref=new Mythread();
Objref.start()
OR
Mythread objref2=new Mythrad();
Thread t=new Thread();
t.start();

Write a java program to achieve multithreading.

class MyThread extends Thread
{
public void run()
{
int a=10,b=20,c;
c=a+b;
System.out.println("this is run method");
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
System.out.println(c);
}
};
class Main
{
public static void main(String args[])
{
MyThread m1=new MyThread(); m1.start(); MyThread m2=new MyThread(); m2.start(); MyThread m3=new MyThread(); m3.start(); } } Output: C:\Documents and Settings\sateesh\Desktop>javac ThreadDemo.java C:\Documents and Settings\sateesh\Desktop>java ThreadDemo this is run method this is run method this is run method 30 30 30
In the above example three threads ( m1,m2,m3) are trying to execute same setoff statements simultaneously with the time gap or time slice.
Sleep method can be used to converting running state into waiting state. Whenever m1 thread is an waiting state that processor will start execute thread and if it is an waiting state processor will start executing the m3 thread that means processor time utilized by executing multiple threads simultaneously.
Note: Start method always calls run method.

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);
}
}
}
}
class Main
{
public static void main(String args[])
{
Demo d=new Demo();
d.start();
}
}
Output:
C:\Documents and Settings\sateesh\Desktop>javac Main.java
C:\Documents and Settings\sateesh\Desktop>java Main
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello sateesh
hello Sateesh

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()
{
add();
System.out.println("z1="+z1);

try
{
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
sub();
System.out.println("z2="+z2);
}
}
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:
C:\Documents and Settings\sateesh\Desktop>javac Main.java
C:\Documents and Settings\sateesh\Desktop>java Main
z1=50
z1=50
z1=50
z2=-10
z2=-10
z2=-10

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()
{
--
--
}
UDTC obj =new UDTC();
Obj.start();
}
class Demo implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("hai sateesh");
try
{
Thread.sleep(3000);
}
catch(InterruptedException id)
{
System.out.println(id);
}
}
}
}
class Main
{
public static void main(String args[])
{
Demo d=new Demo();
Thread t=new Thread(d);
t.start();
}
}

Output:
C:\Documents and Settings\sateesh\Desktop>javac MainThread.java
C:\Documents and Settings\sateesh\Desktop>java MainThread
hai sateesh
hai sateesh
hai sateesh
hai sateesh
hai sateesh
hai sateesh
hai sateesh
hai sateesh
hai sateesh
hai Sateesh


NOTE:
Even thread class also object can be attached if user defined thread class is derived from predefined thread class.

Thread class methods:

  1. setName():
  2. which can be used to set a user defined name for any thread.
    		
    UserdefinedThread objerf=new UserdefinedThread();
    Objerf.setName("MyThread");
  3. getName():
  4. 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,………

  5. setPriority():
  6. 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)
    
  7. getPriority():
  8. 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).
  9. Sleep():
  10. 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)
    {
    --
    }
    }
    
  11. Suspend():
  12. 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.

  13. Resume():
  14. Which can be used to convert waiting state thread to ready state . resume method should be used after using suspend method.
    Syntax:
    Obj.resume();
  15. isAlive():
  16. 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();
  17. currnetThread():
  18. 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.

  19. Join:
  20. Which can be used to combine multiple threads
    Syntax:
    public final void join() throws InterruptedException
    try
    {
    obj.join();
    obj.join(); 
    --
    --
    }
    
  21. Run():
  22. 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()
    {
    --
    --
    }
    
  23. Start():
  24. Which can be used to start the execution of the thread by calling run method.
    Obj.start();

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


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).
    class Reserve implements Runnable
    {
    int available=1;
    int wanted;
    Reserve (int i)
    {
    wanted=1;
    }
    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");
    }
    }
    }
    }
    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 1: Without synchronization block
    C:\Documents and Settings\sateesh\Desktop>java MultiThread
    avalable berts 1
    1 berts reserved for person
    avalable berts 1
    1 berts reserved for person
    Output 1: With synchronization block
    C:\Documents and Settings\sateesh\Desktop>java MultiThread
    avalable berts 1
    1 berts reserved for person
    avalable berts 0
    sorry ! no berths
    Synchronize block:

  • Using synchronized method:
  • Which can be used to all statements of user defined method as synchronize.
    Syntax:
    synchronized returntype methodname(lp/np)
    {
    --
    --
    }
    
    If any method preceded with synchronize keyword then that method become synchronized method and this method will execute by the single thread at a time.

    Write a java program to achieve thread synchronization throws synchronized method.

    class Reserve implements Runnable
    {
    int available=1;
    int wanted;
    Reserve (int i)
    {
    wanted=1;
    }
    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("sorrt ! no berths");
    }
    }
    }
    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: without synchronized method
    C:\Documents and Settings\sateesh\Desktop>javac MultiThread1.java
    C:\Documents and Settings\sateesh\Desktop>java MultiThread1
    avalable berts 1
    1 berts reserved for person
    avalable berts 1
    1 berts reserved for person
    Output: with synchronized method
    C:\Documents and Settings\sateesh\Desktop>java MultiThread1
    avalable berts 1
    1 berts reserved for person
    avalable berts 0
    sorrt ! no berths

Inter Thread Communication:

If one thread is communicating with other thread is known as inter thread communication. In the inter thread communication output one thread becomes input for other thread.
Inter thread communication can be achieved with the following predefined thread.

  1. Wait()
  2. Notify()
  3. Notifyall()
The above three methods are predefined in object class of java.lang package.
  • wait():
  • Which can be used to make ready state thread to waiting state thread. One thread can make another thread into waiting state using wait method.
  • notify():
  • Which can be used to make waiting state method to running state. Using this method one thread can intimate to other single thread to change the state waiting to running.
    class Customer{  
    int amount=10000;  
      
    synchronized void withdraw(int amount){  
    System.out.println("going to withdraw...");  
      
    if(this.amount<amount){  
    System.out.println("Less balance; waiting for deposit...");  
    try{wait();}catch(Exception e){}  
    }  
    this.amount-=amount;  
    System.out.println("withdraw completed...");  
    }  
      
    synchronized void deposit(int amount){  
    System.out.println("going to deposit...");  
    this.amount+=amount;  
    System.out.println("deposit completed... ");  
    notify();  
    }  
    }  
      
    class Main{  
    public static void main(String args[]){  
    final Customer c=new Customer();  
    new Thread()
    {
      
    public void run()
    {c.withdraw(15000);}  
    }.start();  
    new Thread(){  
    public void run(){c.deposit(10000);}  
    }.start();  
      
    }}  	    	    
    	    	
  • notifyAll():
  • which can be used to make waiting state thread into ready state. Using this method one thread can intimate to all the running state threads to change into running state.

volatile keyword:

volatile is a keyword in java language always preceded by data member of class ,which allocates duplicate for the every thread along with common memory. because of this if any thread is changing the resource value that will be never replaced on other thread execution.


NOTE: Volatile keyword should be used only in the thread class and it should be declared the outside the method only
class A extends Thread
{
volatile int x=10;
public void run()
{
volatile int y=1; // not write here
--
--
--
}
}
If any thread is created for above class along with common memory separate duplicate memory will be allocated. Ex: A os=new A();
volatile