Tuesday, February 21, 2017

InterruptedException

This exception is thrown when a thread is in sleep mode and interrupted by another thread. Lets understand this by an example:
create a java file Interrupt.java in dev21century.threading package:
package dev21century.threading;
class Thread1 extends Thread
{
     Thread1(String s)
     {
           super(s);
     }
     public void run()
     {
           System.out.println("Thread Name: " + getName());
           try{
                Thread.sleep(60000 * 10);
           }catch(Exception e)
           {}
           System.out.println("interrupted from class");
           System.out.println("Thread " + getName() + " dead..");
     }
}
class Thread2 extends Thread
{
     Thread1 thread1;
     Thread2(String s, Thread1 thread1)
     {
           super(s);
           this.thread1 = thread1;
     }
     public void run()
     {
           System.out.println("Thread Name  : " + getName());
           thread1.interrupt();
           try{
                Thread.sleep(1000);
           }catch(Exception e) {}
          
           System.out.println("Thread   : " + getName() + " dead.");
     }
}
public class Interrupt {
     public static void main(String args[])
     {
           Thread1 thread1 = new Thread1("thread1");
           thread1.setPriority(10);
           Thread2 thread2 = new Thread2("thread1", thread1);
           thread1.start();
           thread2.start();
          
          
     }
}
Output:

Shutdown hookup In Java

While terminating a program a thread can be invoked, such threads are called shutdown hookup. In this thread we can put some closing codes like closing database or network connection, taking backup etc.

Create a java file ShutdownHooksImpl.java in dev21century.threading package:

package dev21century.threading;

class ShutdownHooks implements Runnable
{
     public void run()
     {
           System.out.println("-- shutdown hookup started..");
           System.out.println("-- Application shutting down..");
           try{
                Thread.sleep(1000*5);
           }
           catch(Exception e)
           {
                System.out.println(e);
           }
     }
}

public class ShutdownHooksImpl {
 public static void main(String args[])
 {
     Runtime runTime = Runtime.getRuntime();
     ShutdownHooks hooks = new ShutdownHooks();
     //Register the shutdown hooks
     runTime.addShutdownHook(new Thread(hooks));
     int x =  100 / 0;
 }
}

Output:
In this program an exception occurred during program execution, even then the shutdown hookup thread got executed.


Task scheduling In Java

This is out of threading concept, threading is not used here. When you will run this example after a delay of 5 seconds a message will be printed in every 1 second:

Create a java file TaskScheduling.java in dev21century.threading package:
package dev21century.threading;

import java.awt.Frame;
import java.util.Timer;
import java.util.TimerTask;
class Task extends TimerTask
{
     int count = 1;
     /*run() is an abstract method
      which defines the task to be executed in scheduled
      interval */
     public void run() {
           System.out.println("Message from timer..");
     }
}

public class TaskScheduling {
     public static void main(String[] args) {

           Timer timer = new Timer();
           int delay = 5000; // 5 seconds
           int period = 1000; //repeate every seconds
           timer.scheduleAtFixedRate(new Task(), delay, period);
          
     }
}

Output:


Daemon Thread

Following characteristics defines the daemon threads:
  1. Daemon threads are service provider threads, they provide services to other threads.
  2. These threads dead automatically if the thread to which they are providing service are dead.
  3. These threads never show any output.
  4. They always run in background.

For example assume a scenario where a client side thread needs to display an image, now here some should be there who brings the image from server / database. So, in this case just create a server side daemon thread which will bring image from the server database.
A real example if daemon thread is relay fielding in cricket match, where one man throws the ball to another and he it throws further.

Java’s garbage collector thread is a daemon thread.

There is a method setDaemon(Boolean) to make a thread as a daemon thread.
For example:

package dev21century.threading;
class DThread1 extends Thread
{     
       DThread1(String threadName)
       {
              super(threadName);
       }
       public void run()
       {
         for(int i = 0;i<5;i++)
          {
           System.out.println("Thread Name: " + getName());
          }
       }
}

public class MainThread {

       public static void main(String[] args) {

        DThread1 dthread1 = new DThread1("DaemonThread1");
       
        dthread1.setDaemon(true);
        //marking this thread as a daemon thread
       
        dthread1.start();
            
        for(int i = 0;i<4;i++)
        {
          System.out.println(Thread.currentThread().getName());
        }            
     }

}

Output:
main
Thread Name: DaemonThread1
main
Thread Name: DaemonThread1
main
main
Thread Name: DaemonThread1
Thread Name: DaemonThread1
Thread Name: DaemonThread1

Try to run this program many times the output may be different.


Monday, February 20, 2017

ThreadGroup In Java

ThreagGroup is a class in java which is used to group the set of threads. In this way we can perform a common type of tasks to all threads at one shot like interrupting them all.
As a real example providing training to multiple students one by one for same course is not advisable, instead group them up and teach them in a class room only once.

Example:
package dev21century.threading;
//thread 1 class
class GThread1 implements Runnable
{
       //run method is the main code of thread
       public void run()
       {
         for(int i = 0;i<5;i++)
          {
           System.out.println("Thread Name: " + Thread.currentThread().getName());
          }
       }
}
//thread 2 class
class GThread2 implements Runnable
{
       public void run()
       {
        for(int i = 0;i<7;i++)
         {
          System.out.println("Thread Name: " + Thread.currentThread().getName());
         }
       }
}

//thread 3 class
class GThread3 implements Runnable
{
       public void run()
       {
        for(int i = 0;i<9;i++)
         {
          System.out.println("Thread Name: " + Thread.currentThread().getName());
         }
       }
}

public class MainThread {

       public static void main(String[] args) {

        ThreadGroup threadGroup = new ThreadGroup("MyThreadGroup");

        Thread gthread1 = new Thread(threadGroup, new GThread1());
        Thread gthread2 = new Thread(threadGroup, new GThread2());
        Thread gthread3 = new Thread(threadGroup, new GThread3());
       
        threadGroup.interrupt();
        /*with this statement, all 3 threads will
        be interrupetd at once.*/
       
        gthread1.start();
        gthread2.start();
        gthread3.start();

        for(int i = 0;i<11;i++)
        {
          System.out.println(Thread.currentThread().getName());
        }            
     }

}

Output:
main
main
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
Thread Name: Thread-0
main
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
Thread Name: Thread-0
main
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
main
main
main
Thread Name: Thread-0
main
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-0
Thread Name: Thread-0