Thread Communication

thread communication deals the problem that if one thread leaves the monitor then how it will tell to the waiting thread that it is now free to get the monitor. java provide interprocess communication machenism through wait() ,notify() and notifyAll() methods. these method are implemented in the object class as final.


notify()
It called by the monitor owner thread to wakes up a single thread that is waiting for this monitor object. If more then one, threads are waiting for this monitor then one of them is chosen to be awakened. The choice is arbitrary.

notifyAll()
It called by the monitor owner thread to wakes up multiple threads waiting for this monitor object.

wait()
Causes current thread to wait until another thread invokes the notify () method or the notifyAll() method for this object. It throws InterruptedException

wait(long timeout)              
Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
it throws InterruptedException

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.

//Thread communication 
class Common
{
    synchronized void hello1(int i,String s)
    {
        System.out.println(i+" Hello1 : "+s);
        notifyAll();
        if(i<10)
        try{wait();}catch(Exception e){}
    }
    synchronized void hello2(int i,String s)
    {
        
        System.out.println(i+" Hello2 : "+s);
        notifyAll();
        if(i<10)
        try{wait();}catch(Exception e){}
    }
}
class MyThreadA extends Thread
{
    Common c=null;
    MyThreadA(Common c)
    {
        this.c=c;  
    }
    public void run()
    {    
        for(int i=1;i<=10;i++)
        c.hello1(i,"MyThreadA ");
    } 
}
class MyThreadB extends Thread
{
    Common c=null;
    MyThreadB(Common c)
    {
        this.c=c;  
    }
    public void run()
    {    
        for(int i=1;i<=10;i++)
        c.hello2(i,"MyThreadB ");
    }    
}
class ThreadCommunication
{
    public static void main(String ar[])
    {
        Common obj=new Common();
        MyThreadA t1=new MyThreadA(obj);       
        MyThreadB t2=new MyThreadB(obj);
        t1.start();
        t2.start();         
    }
}
/*OUTPUT
1 Hello1 : MyThreadA
1 Hello2 : MyThreadB
2 Hello1 : MyThreadA
2 Hello2 : MyThreadB
3 Hello1 : MyThreadA
3 Hello2 : MyThreadB
4 Hello1 : MyThreadA
4 Hello2 : MyThreadB
5 Hello1 : MyThreadA
5 Hello2 : MyThreadB
6 Hello1 : MyThreadA
6 Hello2 : MyThreadB
7 Hello1 : MyThreadA
7 Hello2 : MyThreadB
8 Hello1 : MyThreadA
8 Hello2 : MyThreadB
9 Hello1 : MyThreadA
9 Hello2 : MyThreadB
10 Hello1 : MyThreadA
10 Hello2 : MyThreadB
*/

Java Annotations

Self-Descriptive Coding in java.

Java has introduced the feature called annotation through which elements of a program can be marked to contain some Meta data. This Meta data may be available at compile time or at running time. Now it is possible to provide some information for methods, fields, classes etc. that will be available at processing time. You can annotate your method telling to calling method how to call your method. You can annotate your class to tell something to class loader how to cerate the object of class and for what the object should be used. You can declare fields in you class those may be annotated to get their value from specified source.

New version of java and j2ee has been updated to use annotations. Like EJB, webs services, JPA(java persistence API) etc. New version EJB3.x has been simplified to create the EJB without using any XML file. Because the information required to EJB container are provided by the annotation. EJB programmer annotates his class to provide the JNDI name for EJB. In JPA, programmer annotates their coding to map the object into table. There is no need to define how to map Object data into Database.


How to use it
There are two things one is annotation and second is annotation type. Annotation is the marker entity and annotation-type is declaration about marker entity.

You can create annotation type using @ sign followed by interface keyword and annotation declarations contents. Each method declaration defines an element of the annotation type. Method declaration does not contain any parameter and throws clause. The methods have some limited return types. Primitives, String ,Class, enums, annotation, and arrays of preceding types according to the specification of annotation in JDK 1.5.


//Defining annotation type
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ interface A1{
public String author();
public double version();
}

In the above example
Package java.lang.annotation is imported to access the Target, Retention annotations etc.
Target is being used to define that which portion of program will be annotated by this annotation. Like for class, method or field.
Retantion defines the availability of the annotation. It decides at which time annotation will be discarded, for example run time, compile time etc.
@interface is declaring the annotation A1
Methods author() and version() are elements of annotation A1.


Now following program is showing the use of above declared annotation.

//annotating class using annotation
@A1(author="Hemraj", version=1.0)
class UseAnno1{
public void print(String s){
System.out.println("Hello "+s.toUpperCase());
}
}


Here we used the annotation A1 to provide author name and version for the class. We used the following syntax to use annotation.

@annotation (element1=val1, element2=value2…..)

There may more syntax for deferent types of annotations. We provided value “Hemraj” to the element author and value 1.0 to element version. These elements will available with values at the processing time. We can process annotation to get elements and values at run time.



See the following program that is processing annotation.

class Anno1{
public static void main(String ar[]){
UseAnno1 a1=new UseAnno1();
Class c=a1.getClass();
A1 anno=(A1)c.getAnnotation(A1.class);
System.out.println("Author :"+anno.author());
System.out.println("Version :"+anno.version());
}
}

OUTPUT is :
Author :Hemraj
Version :1.0


The above simple program gets the class of object a1 and then get the annotation by calling getAnnotation() method. This method will take the annotation declaration to create proxy object and it return Object type so we have to cast it as A1 type and the reference of annotation is hold into anno reference variable.

Then we called author() method to get value of author element and version() method to get the value of version element from the object referenced through anno reference variable.

Thread Synchronization using synchronized blocks


In the previous example the Shared class provides synchronized method for threads. Threads do nothing so if share class removes the synchronized then thread object will not be able to access the print method synchronously.
            There is second mechanism by which the thread can provided the synchronization to the any object or block.
class MyThread1 extends Thread
{    
    Shared s;
    MyThread1(Shared s)
    {
        this.s=s;
    }    
    public void run()
    {    
        synchronized(s)
        {
            s.print();
        }
    }
}
class MyThread2 extends Thread
{    
    Shared s;
    MyThread2(Shared s)
    {
        this.s=s;
    }    

    public void run()
    {    
        synchronized(s)
        {
            s.print();
        }
    }
}

class syn
{
    public static void main(String ar[])
    {
        Shared obj=new Shared();
        MyThread1 t1=new MyThread1(obj);
        MyThread2 t2=new MyThread2(obj);
        t1.start();
        t2.start();
    }
}

class Shared
{
    public  void print()
    {
         System.out.print("< Hi ");
         try{Thread.sleep(1000);}catch(InterruptedException e){}
         System.out.print(" Hello >\n");
    }
}
==================================================================================
/OUTPUT
 < Hi  Hello >
 < Hi  Hello >
 */

Thread Synchronization

The mechanism to accomplish the mutual access of shared resource for two or more thread is referred as the synchronization .when two or more thread access single resource then it is ensured that only one thread should access it at a time.


The core concept of synchronization is the monitor. Only one thread can get the access to monitor at a time or we can say only one thread can enter in the monitor at a time. If one thread using the shared resource than it is said to be in the monitor and it acquires the lock on the monitor so no anther thread has the permission to access the shared recourse. When first thread finishes its execution then it release the lock from the monitor and frees the monitor to use by another thread.

In the java all the object have their implicit monitor. So it is easy to synchronize any object or any method of object.
There are two ways in which execution of code can be synchronized:
·         synchronized methods
·         synchronized blocks

synchronized methods

Method that should be accessed by one thread at a time is synchronized by the placing synchronized key word as the access modifier before the method. The thread then access it after acquire the lock for it.
When any thread calls the synchronized method, that thread enters in the monitor and all other threads that try to call same synchronized method at the same instance have to wait. When the thread that entered in the monitor (or that accessing the synchronized resource) returns from the synchronized method, the thread waiting, acquires the monitor. So one time only one thread uses the synchronized method.
Bellow in the given example there is a class Shared which has the method print() to print < hi hello> on the console output. There are two separate thread classes. when the object of these are classes are created the object of the class Shared has to passed through the constructor and the reference of that object is stored in to the s reference variable. Both thread classes implements run method and in the run methods they call the print method of the object of reference in s.

Now the main class creates the object of the Shared class ant the reference is stored in the reference variable obj. after it, objects of thread classes are created and the obj is passed to the constructors of the thread classes. So the reference of the same object is passed for both thread’s objects. Now the reference variable s of each thread object refers the same object. And they are calling the print method of the same object in the run method. At last we can say they are calling same print method. Now at this movement it is our responsibility that we ensure that first thread class the print method then second thread calls it

class MyThread1 extends Thread
{    
    Shared s;
    MyThread1(Shared s)
    {
        this.s=s;
    }    
    public void run()
    {    
        s.print();
    }
}
class MyThread2 extends Thread
{    
    Shared s;
    MyThread2(Shared s)
    {
        this.s=s;
    }    

    public void run()
    {    
        s.print();
    }
}

class sync
{
    public static void main(String ar[])
    {
        Shared obj=new Shared();
        MyThread1 t1=new MyThread1(obj);
        MyThread2 t2=new MyThread2(obj);
        t1.start();
        t2.start(); 
    }
}

class Share
{
    public synchronized void print()
    {
         System.out.print("< Hi ");
         try{Thread.sleep(1000);}catch(InterruptedException e){}
         System.out.print(" Hello >\n");
    }
}
OUTPUT
< Hi  Hello >
< Hi  Hello >

Thread priority

Thread priorities are integer values between 1 and 10 used by the thread scheduler to assign the CPU time for the thread for execute their task. When many threads are executed by the thread scheduler, then the thread scheduler uses the priority associated with thread to decide that how much CPU time should be assigned for particular thread. The thread having the higher priority will execute fast then lower priority because the CPU time assigned to higher priority thread is more then lower priority thread.


Some constants are defined in the thread class for specify the priority values and they can be used to assign the relative priorities among the threads. Those are below with their access specifier and access modifier.

public static final int
MAX_PRIORITY
10
public static final int
MIN_PRIORITY
1
public static final int
NORM_PRIORITY
5

The execution of multiple threads on a single CPU, in some order, is called scheduling. The Java platform supports a simple, deterministic scheduling algorithm called fixed-priority scheduling.

there are following methods those are used to handle the thread priority.
getPriority()
It returns the integer type value which represents the priority associated with thread.
setPriority(int newPriority)
It changes the priority of the thread. The new priority is passed as the integer type argument.

//Thread priority
class MyThread extends Thread
{    int i;
    String msg;
    MyThread(String msg)
    {
        this.msg=msg;
    }
    public void run()
    {    
        while(true)
        {    
            i++;
        }
    }
}
class MyThr
{
    public static void main(String ar[])
    {
        System.out.println("Start main");
        MyThread t1=new MyThread("this is t1 ");
        MyThread t2=new MyThread("this is t2 ");
        t1.setDaemon(true);
        t2.setDaemon(true);
        t1.setPriority(5);   
        t2.setPriority(7);
        t1.start();
        t2.start();   
        try{
            Thread.sleep(500);
        }catch(InterruptedException e){}
        System.out.println("t1 "+t1.i);
        System.out.println("t2 "+t2.i);
        System.out.println("Exit from main");
    }
}
/OUTPUT
 Start main
t1 60239458
t2 1324496589
Exit from main
*/

Joining the threads

If you want that one thread should waits until another thread return from its running process or it die You can do it by using the join() method. If join method is called then the execution stops on that line of code until the thread on which join() called is died .


//join
//Author @ Hemraj
class MyThread extends Thread
{
    String msg;
    MyThread(String msg)
    {
        this.msg=msg;
    }
    public void run()
    {
        for(int i=0;i<10;i++)
        {    
            try
            {
                sleep(500);
            }catch(InterruptedException e){}
            System.out.println(i+msg);
        }
    } 
}

class MyThrea
{
    public static void main(String ar[])
    {
        MyThread t1=new MyThread("this is t1");
        t1.start();
        for(int i=0;i<10;i++)
        {    
            try
            {
                Thread.sleep(500);
                if(i==5)
                    {
                        try{t1.join();}catch(InterruptedException e){}
                    }
            }catch(InterruptedException e){}
            System.out.println(i+"main thread");
        }
        
    }
}

Checking the thread’s life (isAlive())



To check whether a particular thread is in live state or not, at any time we use isAlive() method. This method returns true if the thread for which it called is in the living state and it returns false if the thread is not alive.
//isAlive 
class MyThread extends Thread
{
    public void run()
    {
        for(int i=0;i<10;i++)
        {    
            try
            {
                sleep(500);
            }catch(InterruptedException e){}
        }
    } 
}
class MyThreadTest
{
    public static void main(String ar[])
    {
        System.out.println("Start main");
        MyThread t1=new MyThread();
        t1.start();
        for(int i=0;i<12;i++)
        {    
            try
            {
                Thread.sleep(1000);
            }catch(InterruptedException e){}
            if(t1.isAlive())
                System.out.println("t1 is Alive");
            else
                System.out.println("t1 is not alive");
        }
        System.out.println("Exit from main");
    }
}
/*OUTPUT
Start main
t1 is Alive
t1 is Alive
t1 is Alive
t1 is Alive
t1 is Alive
t1 is not alive
t1 is not alive
t1 is not alive
t1 is not alive
 Exit from main
*/

Basic Thread’s States

Life cycle of the thread is valuable in the large multithreading application. State of a thread specifies the current activities of the thread at any movement. There are four basic state of the thread.
1.     New – when the object of the class that representing a thread after creating the object, is created then before call the start method the thread can’t run. So it is called new state of the thread or in other words we can say that the thread is said to be in new state. It means the thread has been created and it is ready to run.

2.     Runnable --Thread exists in several states. A thread that has been just created is in the new state. The thread remains in this state until the thread’s start method is called. This causes the thread to enter the runnable (ready) state when the system assigns a processor to the thread

  1. Running – A thread is said to be in the running state if it is executing instructions. The instructions are placed in the run method and when the run method is executing, and then the thread is in the running state. The run method is called by the start() method automatically.

  1. Dead- when the thread returns from run method, it is said to be in the dead state. After the return from the run() the thread instance will available for latter use .

  1. Blocked the thread could be run but there is something that prevents it. While in the blocked state the scheduler will simply skip over it and not give it any CPU time. Until a thread re-entered the running state it will not perform any operations.

Checking the thread state

New release 5.0 of java provides the facility to check the state of the thread at any instance. When the method getState() is called on a thread, one of the following Thread.State values is returned:
·         NEW
·         RUNNABLE
·         BLOCKED
·         WAITING
·         TIMED_WAITING
·         TERMINATED


Thread using extending Thread class

Extending the Thread Class

The thread class can be extended to create the thread. A typical procedure for doing this is as follows
1.      A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2.      This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3.      The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.


class A extends Thread{
    public void run(){
        say();
    }
    public void say(){
        for(int i=0;i<10;i++){
            try{Thread.sleep(500);}catch(Exception e){}
            System.out.println("Hello "+i+" times");
        }
    }
}
class B extends Thread{
    public void run(){
        say();
    }
    public void say(){
        for(int i=0;i<10;i++){
            try{Thread.sleep(500);}catch(Exception e){}
            System.out.println("Hi "+i+" times");
        }
    }
}



class ThreadDemo1{
    public static void main(String ar[]){
        A a1=new A();
        B b1=new B();
        //a1.run();
        //b1.run();
        a1.start();
        b1.start();
    }
}



When creating threads, using Thread class there are two Disadvantages
·         Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
·         A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.

Thread Creation using Runnable interface




In java programming there are something predefined which is used to create a thread. The thread in java represent by the Object of your class which has the Thread property. So when you create a thread you have to just put some extended properties in your class due to which the behavior of Object of your class is like the thread.

There are two ways to create a thread.
  • First is , Implements Runnable interface in to your class, and defined run method declared by it
  • Second is Extends Thread class in to your class and override the run method.

Runnable interface

Runnable interface comes from java.lang package. Runnable interface has only one method declaired as follow

public interface Runnable
{
     public void run();
}
So to make a thread using the Runnable interface you have to define the run method. The run method is necessary to be thread of a normal class.
A thread, which is created based on an object that implements the Runnable interface, will execute the code defined in the public method run(). In other words, the code in the run() method defines an independent path of execution and thereby the entry and the exits for the thread. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
The steps for creating threads using Runnable interface is as follows:
1.      A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2.      An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3.      The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.

class A implements Runnable{
    public void run(){
        say();
    }
    public void say(){
        for(int i=0;i<10;i++){
            try{Thread.sleep(500);}catch(Exception e){}
            System.out.println("Hello "+i+" times");
        }
    }
}
class B implements Runnable{
    public void run(){
        say();
    }
    public void say(){
        for(int i=0;i<10;i++){
            try{Thread.sleep(500);}catch(Exception e){}
            System.out.println("Hi "+i+" times");
        }
    }
}





class ThreadDemo1{
    public static void main(String ar[]){
        A a1=new A();
        B b1=new B();
        Thread t1=new Thread(a1);
        Thread t2=new Thread(b1);
        t1.start();
        t2.start();
    }
}

Popular Posts