Friday, 4 July 2014

Java Thread Tutorial

There are N number of tutorials and material  on the Internet on Threads, but i found some difficulties in terms of terminology and examples given by some of the tutorials, So i want to make it simple useful for beginners and i want to give some information points-wise that might helps to the job seeker, So lets starts with the definition of the Thread.

Thread:
   1. Thread is a light weight process.
   2. Thread is a java object it has variables and methods, it lives and dies in the   heap memory.
  3. Each thread has own call stack.

Difference between Thread and Process:

 .  Process has its own memory space and set of runtime resources(A process may contains multiple Threads or at least one Thread).
 .  Threads exist within a process.Threads share the process's                               resources,including  memory and open files.

Creating Thread:
                Thread can be created in two ways
                        1.extending Thread class
                        2. implementing Runnable interface.
extending Thread:
              class MyThread extends Thread {
                     public void run() {
                    System.out.println("Important job running in MyThread");
                       }
                   }
            in this approach we need to override the run() method as above. When Thread started running, the code in run() method will be executed.

Note: extending a Thread is not a good option, because java does not support multiple inheritence so if you extend Thread you cannot extend any other class.

implementing Runnable interface.

class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
}
}
Creating object of Thread:
           if you create a Thread by extending Thread class then instantiating is very simple as shown below:
              MyThread t = new MyThread();
         if you create a Thread by implementing Runnable interface, then instantiating is  as shown below:

 MyRunnable r = new MyRunnable();//create Runnable object and
 Thread t = new Thread(r); // Pass your Runnable to the Thread


Thread functions:
     As we discussed in point no 2. Thread is a java class, so some of its frequently used methods are:
                start()
                yield()
                sleep()
                run()

We have already seen the run() method when creating thread. So if you want to create a thread you should override the run() method, and run() method belongs to Thread class. In a little while we will see all of these methods usage.



Starting Thread: 
So far we have seen that how to create thread and how to instantiate Thread. now we are going to see how to start the Thread. To start  a thread we must invoke the start() method of the Thread class.

ex:  t.start(); here t is instance of the Thread class.


Now its time to bind all these togather:

public class ThreadSample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t = new Thread(myRunnable);// Thread is in New State
        t.start();//Thread is in Runnable State.
    }
}

class MyRunnable implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example");
            //Thread is in Running State.
        }
       
    }
   
}

Thread States: Thread always in one of the five states.

     New state
     Runnable state
     Running state
     Blocked or Wait state
     Dead state.

    New --->Runnable<----->Running------->Dead
                      \                      /
                       \                   /
                      Blocked or Waiting
New state: When the thread is instantiated

Runnable state: When thread is invoke start() method. In this state Thread is ready to run, Thread may come here from New state or Running state or from
Blocked state.

Running state: When the Scheduler pick the Thread from Runnable pool and executed the code inside run() method.

Bocked state: the thread is still alive, but is currently not eligible to run. Thread comes to this state from Running state and there are some functions in Thread class to send a Thread from Running state to Blocked state.


Dead state:
A thread is considered dead when its run() method completes. A dead thread cannot be started again.


MultiThread Example:

public class ThreadSample {
    public static void main(String[] args) {
        MyRunnableOne myRunnableOne = new MyRunnableOne();
       MyRunnableTwo myRunnableTwo = new MyRunnableTwo();
       MyRunnableThree myRunnableThree = new MyRunnableThree();

        Thread tOne= new Thread(myRunnableOne);
        tOne.start();

        Thread tTwo= new Thread(myRunnableTwo);

        tTwo.start();

        Thread tThree= new Thread(myRunnableThree);

        tThree.start();

    }
}

class MyRunnableOne implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example One");
            //Thread is in Running State.
        }
       
    }
   
}

class MyRunnableTwo implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example Two");
            //Thread is in Running State.
        }
       
    }
   
}


class MyRunnableThree implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example Three");
            //Thread is in Running State.
        }
       
    }
   
}

 The out put would remain unexpected, for each run it would give you a different out put. When we call the start method on thread object it will enters into Runnable state and waits for its turn, Based on some criteria scheduler will pick one of the thread waiting for chance in the Runnable pool and give its time to the selected thread, When the thread is in Running it may require some i/o operations in that case scheduler sends the Running state to Blocked state.

Now its time to look into some of the Thread methods:

Sleep: Sleep() method is a static method in Thread class
try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }

Notice that the sleep() method can throw a checked InterruptedException.

When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds. After the specified time in the sleep() mehtod thread will enter into the Runnable state. So minimum time enter into the running state of Thread after sleep is (sleepTime+someTime).

i.e (5*60*1000) + some time
i.e once the specified time is over thread is enter into the Runnable state and waiting for its chance, then the scheduler will decide  when to this thread get back to Running state.


Example:

public class ThreadSample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        Thread t2 = new Thread(myRunnable);
        t1.setName("First Thread");
        t2.setName("Second Thread");
        t1.start();
        t2.start();
    }
}

class MyRunnable implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName());
            try{
                Thread.sleep(100);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
       
    }
   
}

yield():

Thread always runs with some priority, usually the priority would be 1 to 10.
in Thread class declared some static fields as follows.


Thread.MIN_PRIORITY      (1)
Thread.NORM_PRIORITY         (5)
Thread.MAX_PRIORITY         (10)



we can set the Thread priority as
t.setPriority(8); or t.setPriority(Thread.MAX_PRIORITY);


Now the responsibility of the yield() method is moving the current running Thread to Runnable state. So the scheduler can pick another Thread which is having same or higher priority Thread and waiting for chance to get its turn from the Runnable pool.

Note: yield() method won't ever cause Thread to enter into blocked state.


      Runnable<------------------Running
                          yield()

join():
join() method is non static method of Thread class,
 ex: Thread t = new Thread();
       t.start();
       t.join();

 join() method joins the one thread to the end of the another Thread. I will explain with a simple example

 Suppose A and B are two Threads, Now i want to postponed the B execution to end of the A Thread execution.(i.e) B should be joined at the end of the A.

Example:

    public static void main(String[] args) throws InterruptedException {
        JoinThread t = new JoinThread();
        t.start();
        t.join();
        for(int i=0;i<5;i++){
            System.out.println("I am in MainThread");
        }
       
    }
   
}
class JoinThread extends Thread {
    @Override
    public void run() {
       for(int i=0;i<5;i++){
           try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
           System.out.println("I am in subThread");
       }
    }
}

In the above example There are two threads,
 1.Main Thread
 2. JoinThread.
the Main Thread will be joined at the end of the JoinThread, for testing execute the above program by commented out the t.join() line and watch the out put, i am sure you will get a different out put.

Note: t.join() method should call after starting the Thread, other wise it won't effect.(i.e) t.start(); t.join();

A little Complicated Example:

public class ThreadJoinTest {
    public static void main(String[] args) {
        ThreadOne t1 = new ThreadOne();
        Thread2 t2 = new Thread2(t1);
        Thread t = new Thread(t2);
        t.start();
      
    }
}
class ThreadOne implements Runnable{

    @Override
    public void run() {
      for(int i=0;i<20;i++){
          try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          System.out.println("Thread1");
      }
       
    }
   
}
class Thread2 implements Runnable{
    ThreadOne t1;
    Thread2(ThreadOne t1){
       this.t1 = t1;
    }
    @Override
    public void run() {
        Thread t11 = new Thread(t1);
        t11.start();
        try {
            t11.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i=0;i<20;i++){
         
            System.out.println("Thread2");
        } 
    }
   
}

here commented out  t11.join(); this line in code and see you  observe a different result.

Thread Tutorial part2