Threads in Java Part 2

Thread Properties

In the previous blog we learned about the Thread, the life cycle of thread, the creation of thread, etc. If you want to learn more about Threads, visit Threads in Java. In this, we will go through the basic concept of thread, multithreading, etc.



Thread Properties

  1. Interrupting Thread
  2. When the thread is waiting or sleeping state and if the interrupt() method is called on the thread, then it breaks out the sleeping or waiting state and throws the exception called InterruptedException. However, if the thread is not in a waiting or sleeping state and the interrupt() method is called, it will behave normally and will not interrupt, but it sets the interrupt flag to true. Now we will see the different scenarios where the thread can be interrupted.

    Scenario 1 - Interrupting the thread that does not stop working - In this scenario, the InterruptedException will be handled using try and catch block due to which the thread will not stop working.

    e.g.

    class InterruptThreadEx extends Thread {
      public void run(){
        try {
          int value =0;
          for (int i = 0; i < 5; i++) {
            value = i*2+1;
            System.out.println("The value is:"+ value);
            Thread.sleep(500);
          }
        }catch (InterruptedException e) {
          System.out.println("InterruptedException");
        }
      }
    }
    class InterruptThreadExTest {
        public static void main(String[] args) throws InterruptedException{
       	 InterruptThreadEx threadObj = new InterruptThreadEx();
       	 threadObj.start();
       	 threadObj.interrupt();
        }
    }

    Output

    The value is:1
    InterruptedException

    Scenario 2 - Interrupting the thread that stops working - In this scenario the thread will stop working when the new exception will be thrown.

    e.g

    class InterruptThreadEx extends Thread {
      public void run(){
        try {
          int value =0;
          Thread.sleep(1000);
          for(int i=0;i<4;i++){
            value = i*i;
            System.out.println("The value is:" + value);
          }
        }catch (InterruptedException e) {
          throw new RuntimeException("Thread Interrupted due to unknown event");
        }
      }
      public static void main(String args[]){
        InterruptThreadEx threadObj = new InterruptThreadEx();
        threadObj.start();
        try {
          threadObj.interrupt();
        }catch (Exception e) {
          System.out.println("Handled the exception");
        }
      }
    }

    Output

    Exception in thread "Thread-0" java.lang.RuntimeException: Thread Interrupted due to unknown event
    at InterruptThreadEx.run(InterruptThreadEx.java:13)
  3. Daemon Thread
  4. Daemon Thread runs as a low-priority thread and is a background service thread that performs background operations like garbage collection, etc. JVM exists only when all the threads running are demon threads.

    setDaemon() - setDaemon() method is used to set the particular thread as a daemon thread or user thread. This method should be before the start of the thread.

    e.g

    public class DaemonThreadEx extends Thread{
      String str;
      public DaemonThreadEx(String name){
        str = name;
      }
      public void run(){
        if(Thread.currentThread().isDaemon()){
          System.out.println(str + " is Daemon thread");
        }
        else{
          System.out.println(str + " is User thread");
        }
      }
      public static void main(String[] args){
        DaemonThreadEx thread1 = new DaemonThreadEx("Thread1");
        DaemonThreadEx thread2 = new DaemonThreadEx("Thread2");
        thread1.setDaemon(true);
        thread1.start();
        thread2.start();
      }
    }

    Output

    Thread1 is Daemon thread
    Thread2 is User thread
  5. Handlers for Uncaught Exceptions
  6. We have already learned about the exception in our previous blogs. So the exception is nothing but the unwanted event that occurs during the execution of the program at run time, due to which the normal flow gets affected. The run() method cannot throw a checked exception but due to an unchecked exception, it can get terminated. As the thread gets terminated it dies. Here no catch block is available instead exception is passed to the handler for uncaught exceptions just before the termination of thread. The handler which will be used must belong the class that implements the Thread.UncaughtExceptionHandler interface. The Thread.UncaughtExceptionHandler interface has the method called setDefaultUncaughtExceptionHandler() method. The argument of setDefaultUncaughtExceptionHandler() method is used to override the way JVM handles the uncaught exceptions.

    e.g

    class UncaughtExceptionEx implements Thread.UncaughtExceptionHandler{
      public void uncaughtException(Thread t, Throwable e){
        System.out.println("Welcome to Java Blog");
      }
    }
    public class UncaughtExceptionExTest {
      public static void main(String[] args)throws Exception{
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionEx());
        throw new Exception("Exception");
      }
    }

    Output

    Welcome to Java Blog
    Exception
  7. Thread Priorities
  8. Priority is nothing but the importance given to a particular thing. The same concept is applicable in Java too. In Java, each thread has a priority. The priorities of the thread are set between 1 to 10. We can increase and decrease the priority of the thread by using the setPriority() method. The thread having a priority of 1 is considered less important and a priority of 10 is considered the most important. There are three constants used for defining the priorities.

    1. MIN_PRIORITY - MIN_PRIORITY has a low priority with the value of 1.
    2. NORM_PRIORITY - NORM_PRIORITY has the default priority with the value of 5. If the programmer doesn’t set the priority explicitly then the JVM automatically set the default priority to the thread.
    3. MAX_PRIORITY - MAX_PRIORITY has the highest priority with a value of 10.
    4. e.g

      class ThreadPriorityEx extends Thread{
        public void run(){
          System.out.println("Welcome to Java Blog");
        }
        public static void main(String args[]){
          ThreadPriorityEx thread1=new ThreadPriorityEx();
          ThreadPriorityEx thread2= new ThreadPriorityEx();
          ThreadPriorityEx thread3= new ThreadPriorityEx();
          ThreadPriorityEx thread4= new ThreadPriorityEx();
          thread1.setPriority(Thread.MIN_PRIORITY);
          thread2.setPriority(Thread.MAX_PRIORITY);
          thread3.setPriority(6);
          System.out.println("Thread Priority:" +thread1.getPriority());
          System.out.println("Thread Priority:" +thread2.getPriority());
          System.out.println("Thread Priority:" +thread3.getPriority());
          System.out.println("Thread Priority:" +thread4.getPriority());
        }
      }

      Output

      Thread Priority:1
      Thread Priority:10
      Thread Priority:6
      Thread Priority:5

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.