***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***

posts

    Thread Priorities

    Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

    Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

    public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

    public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

    A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU. A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.

    Thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

    Ex:

    import java.lang.*; 

    public class ThreadPriorityExample1 extends Thread  

    { 

     public void run() 

    { 

    System.out.println("Inside the run() method"); 

    } 

    public static void main(String argvs[]) 

    { 

    Thread.currentThread().setPriority(7); 

    System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority()); 

    ThreadPriorityExample1 th1 = new ThreadPriorityExample1(); 

    System.out.println("Priority of the thread th1 is : " + th1.getPriority()); 

    } 

    }

    Life Cycle of a Thread

    1. New: In this state, a new thread begins its life cycle. This is also called a born thread. The thread is in the new state if you create an instance of Thread class but before the invocation of the start() method.

    A thread can be killed using stop() method. 

    2. Runnable: A thread becomes runnable after a newly born thread is started. The thread in runnable state joins the queue of threads waiting for processor.

    A thread can be executed before its turn using yeild() method.

    3. Running: When the thread scheduler selects the thread then, that thread would be in a running state and execution of a thread starts.

    A running thread can be suspended using suspend() method. A suspended thread can resume its execution using resume() method.

    A running thread can be made to sleep for specific period of time using sleep(time) method, the thread enters suspend state. After given time is elapsed thread automatically enters into runnable state.

    A running thread is made to wait using wait() method, it will be in wait state until an event is occurred. A waiting thread can be resumed using notify() method.

    4. Blocked: The thread is still alive in this state, but currently, it is not eligible to run.

    5. Terminated: A thread is terminated due to the following reasons:

    • Either its run() method exists normally, i.e., the thread’s code has executed the program.
    • Or due to some unusual errors like segmentation fault or an unhandled exception.
    A thread will be killed using stop() method.

    Ex:

    A1.java

    class A1 extends Thread {

    public void run() {

    System.out.println("Thread A");

    System.out.println("i in Thread A ");

    for (int i = 1; i <= 5; i++) {

    System.out.println("i = " + i);

    try {

    Thread.sleep(1000);

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

    System.out.println("Thread A Completed.");

    }

    }

     

    B1.java

    class B1 extends Thread {

    public void run() {

    System.out.println("Thread B");

    System.out.println("i in Thread B ");

    for (int i = 1; i <= 5; i++) {

    System.out.println("i = " + i);

    }

    System.out.println("Thread B Completed.");

    }

    }

     

    ThreadLifeCycleDemo.Java

    public class ThreadLifeCycleDemo {

    public static void main(String[] args) {

    A1 threadA = new A1();

    B1 threadB = new B1();

    threadA.start();

    threadA.yield();

    try {

    threadA.sleep(1000);

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    threadB.start();

    System.out.println("Main Thread End");

    }

    }

    Multithreading in Java

    A thread in Java is a lightweight process requiring fewer resources to create and shares the process resources.

    A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

    Threads use a shared memory area which helps to save memory, and also, the content-switching between the threads is a bit faster than the process.

    In Java, Multithreading refers to a process of executing two or more threads simultaneously for maximum utilization of the CPU.

    Advantages of Multithreading are:

    • Multithreading saves time as you can perform multiple operations together.
    • The threads are independent, so it does not block the user to perform multiple operations at the same time and also, if an exception occurs in a single thread, it does not affect other threads.

    There are two ways to create a thread:

    1. By extending Thread class
    2. By implementing Runnable interface.

    The first is to create a subclass of Thread and override the run() method. The second method is to pass an object that implements Runnable (java.lang.Runnable) to the Thread constructor.

    Thread class:

    Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

    The first is to create a subclass of Thread and override the run() method. The run() method is executed by the thread start() call is made.

     

    Ex:

    public class Mythread extends Thread {

      public static void main(String[] args) {

        Mythread thread = new Mythread();

        thread.start();

        System.out.println("This code is outside of the thread");

      }

      public void run() {

        System.out.println("This code is running in a thread");

      }

    }

    Runnable Interface Implementation:

    A Java object that implements the Runnable interface can be executed by a Java Thread. The Runnable interface is a standard Java Interface that comes with the Java platform. The Runnable interface only has a single method run().

    Whatever the thread is supposed to do must be included in the implementation of the run() method.

    If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method

    Ex:

    public class Mythrea implements Runnable {

      public static void main(String[] args) {

        Mythread obj = new Mythread();

        Thread thread = new Thread(obj);

        thread.start();

        System.out.println("This code is outside of the thread");

      }

      public void run() {

        System.out.println("This code is running in a thread");

      }

    }

    User defined exception in java

    User Defined Exception or custom exception is creating user own exception class and throws that exception using ‘throw’ keyword. User-defined exception must extend Exception class.

    In order to create custom exception, it is needed to extend Exception class that belongs to java.lang package.

     

    Ex:

    class JavaException{

       public static void main(String args[]){

      try{

           throw new MyException(2);

           // throw is used to create a new exception and throw it.

      }

     catch(MyException e){

        System.out.println(e) ;

     }

    }

    }

    class MyException extends Exception{

       int a;

       MyException(int b) {

         a=b;

       }

       public String toString(){

         return ("Exception Number =  "+a) ;

      }

    }

     

    Exception Handling in Java

    An exception is defined as an abnormal condition that may happen at runtime and disturb the normal flow of the program.

    An exception can occur for many different reasons. Following are some scenarios where an exception occurs.

    • A user has entered an invalid data.
    • A file that needs to be opened cannot be found.
    • A network connection has been lost in the middle of communications or the JVM has run out of memory.

    The Exception Handling in Java is a mechanism to handle the runtime errors so that the normal flow of the application can be maintained.

    There are three categories of exceptions:

    • Checked exceptions − a checked exception is an exception that is checked (notified) by the compiler at compilation-time; these are also called as compile time exceptions. These exceptions should be taken care of (handle) by programmers.
    • Unchecked exceptions − an unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
    • Errors − these are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in code because rarely anything can be done about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

     

    Hierarchy of Java Exception classes

     

    All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

     

    Java Exception Keywords

    Java provides five keywords that are used to handle the exception – try, catch, finally, throw, throws.

     

    The ‘try’ keyword is used to specify a block where an exception code is placed and this block must be followed by either catch or finally.

     

    The "catch" block is used to handle the exception. It must be preceded by try block. It can be followed by finally block later.

     

    try {

       // Protected code

    } catch (ExceptionName e1) {

       // Catch block

    }

     

    Ex:

    import java.io.*;

    public class ExcTest {

       public static void main(String args[]) {

          try {

             int a[] = new int[2];

             System.out.println("Access third element:" + a[3]);

          }catch (ArrayIndexOutOfBoundsException e) {

             System.out.println("Exception thrown  :" + e);

          }

          System.out.println("Out of the try block");

       }

    }

     

    A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −

     

    Syntax:

    try {

       // Protected code

    } catch (ExceptionType1 e1) {

       // Catch block

    } catch (ExceptionType2 e2) {

       // Catch block

    } catch (ExceptionType3 e3) {

       // Catch block

    }

     

    The "throw" keyword is used to throw an exception.

    Example:

    public class ExceptionDemo {

                static void canVote(int age){

                if(age<18)

                try{

                    throw new Exception();

                }catch(Exception e){

                    System.out.println("you are not an adult!");

                }

                else

                               System.out.println("you can vote!");

                }

                public static void main (String[] args) {

                            canVote(20);

                            canVote(10);

                }

    }

     

    The "throws" keyword is used to declare exceptions. It specifies that an exception may occur in the method. It doesn't throw an exception. It is always used with method signature. Throws keyword is used when callee doesn’t want to handle the exception rather it wants to extend this responsibility of handling the exception to the caller of the function.

     

    Ex:

    public class ExceptionDemo {

                static void func(int a) throws Exception{

                               System.out.println(10/a); 

                }

                public static void main (String[] args) {

                            try{

                                func(10);

                                func(0);

                            }catch(Exception e){

                               System.out.println("can't divide by zero");

                            }

               

                }

    }

     

    The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

    A finally block appears at the end of the catch blocks and has the following syntax –

     

    try {

       // Protected code

    } catch (ExceptionType1 e1) {

       // Catch block

    } catch (ExceptionType2 e2) {

       // Catch block

    } catch (ExceptionType3 e3) {

       // Catch block

    }finally {

       // The finally block always executes.

    }