© People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1
Day 5 Exception Handling Threads
Exception Handling
Errors and Exception • A programmer can make following types of error in the program: • Logical errors • Compilation errors • Runtime errors • Logic errors are errors that prevent the program from doing what is intended do. • If a program has logical errors, the code may compile and run without error, but the result of an operation may not produce a expected result. • Compilation errors are error that get raised when the syntax is incorrect.
Errors and Exception (Contd.) • Compilation errors prevent the program from compiling. • Runtime errors are errors that occur during the execution of a program and disrupts the normal flow of instructions. • Runtime errors occur when your program attempts an operation that is impossible to carry out. • Runtime error also called as exception. • The logical errors and compilation errors can be rectified. • Runtime errors should be handled by the program.
Errors and Exception (Contd.) • To work with exception Java provide various classes: java.lang.Throwable java.lang.Error java.lang.NoClassDefFoundError java.lang.VirtualMachineError java.lang.Exception java.lang.RuntimeException java.lang.ArithmeticException java.lang.IndexOutOfBoundsException java.io.IOException java.io.FileNotFoundException
Errors and Exception (Contd.) • The Throwable class is the base class for all exception classes. • The Exception and Error classes are two sub classes for Throwable. • The sub classes of Error class represents an unusual situations, such as JVM running out of memory. These type of errors are not usually caused by the program errors. • The sub classes of Exception class represents program errors or errors raised because a some resource is not available, such as the file to be accesses is not available.
Errors and Exception (Contd.) • The RuntimeException is a sub class of Exception class. • The RuntimeException and its sub classes represent errors that may be raised to due to program error. For example, dividing a number by zero and accessing an array element outside the range of array.
Checked and Unchecked Exception • Checked exceptions are those exceptions for which providing exception handlers is mandatory. • Checked exceptions should be either caught or be declared to be thrown. • Unchecked exceptions are those exception for which providing exception handlers is optional. • All exceptions of type RunTimeException or its subclasses are unchecked Exceptions.
Handling Exceptions • To handle exceptions Java provides following exceptional handler components: • try block • catch block • finally block • The structure of exception handler component is: try { } catch (ExceptionType name) { } catch (ExceptionType name) { } finally{ }
Handling Exceptions (Contd.) • The code that might throw an exception, should be added inside the try block. • The catch block is an exception handler that handles the type of exception indicated by its argument. • The finally block always gets executed irrespective of an exception raised. • Therefore, a finally block can be used to perform clean up operations, such as closing a file or releasing a network socket. • A try block can be associated with one or more catch blocks and one finally block.
Handling Exceptions (Contd.) • An example to handle unchecked exception: public class ExceptionDemo { public static void main(String args[]){ try{ int c=10/0; System.out.println("Value="+c); }catch(ArithmeticException e){ System.out.println("Catch Block:"+e); } finally{ System.out.println("finally block"); } } }
Handling Exceptions (Contd.) • The preceding code output will be: Catch Block:java.lang.ArithmeticException: / by zero finally block • In the preceding code, if the statement, int c=10/0;, is modified to int c=10/1;, then the output will be: Value=10 finally block
Handling Exceptions (Contd.) • In the preceding code, the catch block can be modified as shown in the following code snippet: catch(ArithmeticException e){ System.out.println("Catch 1:"+e); e.printStackTrace(); } • Here, printStackTrace() method will print the stack trace from where the exception occurred. The output after modifying the code will be: Catch Block:java.lang.ArithmeticException: / by zero finally block java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:4)
Handling Exceptions (Contd.) • An example to handle unchecked exception with multiple catch blocks: public class ExceptionDemo { public static void main(String args[]){ try{ String s=new String("10"); int i=new Integer(s); int c=i/0; System.out.println("Value="+c); }
Handling Exceptions (Contd.) catch(ArithmeticException e){ System.out.println("Catch 1:"+e); }catch(RuntimeException e){ System.out.println("Catch 2:"+e); } finally{ System.out.println("finally block"); } } }
Handling Exceptions (Contd.) • The preceding code output will be: Catch 1:java.lang.ArithmeticException: / by zero finally block • In the preceding code, if the statement, String s=new String("10");, is modified to String s=new String("hello");. Then, the output will be: Catch 2:java.lang.NumberFormatException: For input string: "hello" finally block
Handling Exceptions (Contd.) • Consider the following code: public class ExceptionDemo { public static void main(String args[]){ try{ int c=10/0; System.out.println("Value="+c); }catch(RuntimeException e){ System.out.println(e); } catch(ArithmeticException e){ System.out.println(e); } finally{ System.out.println("finally block"); } } }
Handling Exceptions (Contd.) • The preceding code will generate a compilation error because the handler of the most specific type should always be placed before the general exception type.
Handling Exceptions (Contd.) • Consider the following code: public class ExceptionDemo { static void divide(){ try{ String s=new String("10"); int i=new Integer(s); int c=i/0; System.out.println("Value="+c); }catch(ArithmeticException e){ System.out.println(e); } finally{ System.out.println("Sub finally block"); } }
Handling Exceptions (Contd.) public static void main(String args[]){ try{ divide(); } catch(RuntimeException e){ System.out.println(e); } finally{ System.out.println("Main finally block"); } } }
Handling Exceptions (Contd.) • The preceding code output will be: java.lang.ArithmeticException: / by zero Sub finally block Main finally block • In the preceding code, the statement, String s=new String("10");, is modified to String s=new String(“java");, the output will be: Sub finally block java.lang.NumberFormatException: For input string: "java" Main finally block
Multi Catch • In Java 7 and later versions, a single catch can handle multiple types of exception. • The multi catch feature reduce codes duplication. • The multi catch syntax: try { } catch(<ExceptionType name> | <ExceptionType name> <reference name>) { }
Multi Catch (Contd.) • An example to work with multi catch public class Test { public static void main(String args[]){ int divident[]={10,2,5,20,45}; int divisor[]={0,1,2}; try{ int q=divident[1]/divisor[3]; System.out.println("Value="+q); }
Multi Catch (Contd.) • catch(ArithmeticException | ArrayIndexOutOfBoundsException e){ System.out.println(e); }catch(RuntimeException e){ System.out.println(e); } finally{ System.out.println("finally1"); } } }
Multi Catch (Contd.) • The preceding code output: java.lang.ArrayIndexOutOfBoundsException:3 finally1 • In the preceding code, if the statement, int q=divident[1]/divisor[3];, is modified to int q=divident[1]/divisor[0];, then the code will generate following output: java.lang.ArithmeticException: / by zero finally1
Use of throw and throws • The throw statement is used to explicitly throw an exception. • The throw statement requires an argument of a Throwable object. • The throw statement can be used within the method, catch block, or finally block. • The throws statement is used to propagate an exception. • The throws statement is used with the method signature.
Use of throw and throws (Contd.) • An example to work with throw statement: class ThrowDemo{ public static void main(String args[]) { try { int age=12; if(age <= 18) throw new ArithmeticException(); else System.out.println("Eligible for voting"); } catch(ArithmeticException e) { System.out.println("U r not eligible for voting: "+e); } } }
Use of throw and throws (Contd.) • The preceding code output will be: U r not eligible for voting: java.lang.ArithmeticException
Use of throw and throws (Contd.) • An example to re-throw an exception: import java.io.*; class ThrowDemo{ static void check(){ try { int age=12; if(age <= 18) throw new ArithmeticException(); else System.out.println("Eligible for voting"); } catch(ArithmeticException e) { System.out.println("U r not eligible for voting: "+e); throw e; } }
Use of throw and throws (Contd.) public static void main(String args[]){ try{ check(); System.out.println("After the check() call"); } catch(RuntimeException e) { System.out.println("Main Catch "+e); } } }
Use of throw and throws (Contd.) • The preceding code output will be: U r not eligible for voting: java.lang.ArithmeticException Main Catch java.lang.ArithmeticException
Use of throw and throws (Contd.) • Consider the following code snippet: import java.io.*; class ThrowsDemo { public static void main(String args[]){ FileInputStream fis = null; fis = new FileInputStream("abc.txt"); fis.close(); } } • The preceding code will generate compilation errors because the code would raise an exception, java.io.FileNotFoundException, if the text file is not found.
Use of throw and throws (Contd.) • The exception, java.io.FileNotFoundException is a checked exception. • Therefore, it must be declared as an exception that may be thrown by the method. • In the preceding code, main method should be modified as shown in the following code snippet: public static void main(String args[])throws IOException{ • The throws statement is used to declare an exception that may be thrown by the method.
Use of throw and throws (Contd.) • Consider the following code snippet: class Base{ void print() throws ArithmeticException{ System.out.println("Base Print"); } } class Sub extends Base{ void print() throws Exception{ System.out.println("Sub Print"); } }
Use of throw and throws (Contd.) • The preceding code will raise a compilation error because the overridden method is throwing a broader exception. • While declaring exceptions in overridden methods, the overridden method can reduce or eliminate the exception declaration. However, the overridden methods must not throw a new or broader checked exception. • The throws statement can be used to declare multiple exception as shown in the following code snippet: void print() throws Exception,RuntimeException{ System.out.println("Base Print"); }
Automatic Resource Management in Java7 • The try-with-resources statement is a try statement that declares one or more resources. • A resource is an object that must be closed after the program is finished with it. • The try-with-resources statement ensures that each resource is closed at the end of the statement. • Any object that implements java.lang.AutoCloseable can be used as a resource in try-with-resources statement .
Automatic Resource Management in Java7 • An example code snippet to use try-with-resource statement: try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } • In the preceding code snippet, the BufferedReader class instance is declared in a try-with-resource statement. This will ensure the connection is closed regardless of whether the try statement completes normally or abruptly.
Create Custom Exceptions • Java allows to create a custom exceptions, if an exception type is not represented by Java platform. • A custom exception can be created by creating a sub class of an existing exception class.
Create Custom Exceptions (Contd.) • An example to work with custom exception: public class CustomException extends Exception { public CustomException() { System.out.println("CustomException"); } public CustomException(String message) { super(message); } }
Create Custom Exceptions (Contd.) public class CustomExceptionTest { public static void main(String[] args) { try { testException(null); } catch (CustomException e) { e.printStackTrace(); } } public static void testException(String string) throws CustomException { if(string == null) throw new CustomException("The String value is null"); } }
Create Custom Exceptions (Contd.) • The preceding code output will be: CustomException: The String value is null at CustomExceptionTest.testException(CustomExceptionTest. java:18) at CustomExceptionTest.main(CustomExceptionTest.java:7)
Threads
Introduction to Threads • A thread can be defined as a path of execution in a program. In other words, a thread is a single sequential flow of control within a program. • Example: • When you are performing multiple tasks on a computer, such as listening to music, writing a document, printing another document, and installing a software, each of these tasks are performed as a single thread by the CPU. Thread 1 Thread 2 Thread 3 Thread 4 Playing Music Writing Document Printing Document Installing Software
Thread Class and Runnable Interface • In a Java program, you can create multiple paths of execution by creating threads. • To create a thread in a Java program, you can extend the Thread class. • However, if a class in which you need to create a thread already extends another class, you cannot extend the Thread class to create threads as Java does not support multiple inheritance. • The alternate is to implement the Runnable interface to create threads in the class.
Thread Class and Runnable Interface (Contd.) • The Thread class is defined in the java.lang package. • The Thread class defines several methods that can be overridden by a derived class. • Example: class ThreadCreator extends Thread{ ThreadCreator(){ super("ChildThread"); // Creates new thread System.out.println("ChildThread:" + this); start(); }
Thread Class and Runnable Interface (Contd.) public void run(){ System.out.println("The child thread started"); System.out.println("Exiting the child thread"); }} public class ThreadTest { public static void main(String[] args){ new ThreadCreator(); System.out.println("The main thread started"); System.out.println("The main thread sleeping");
Thread Class and Runnable Interface (Contd.) try{ Thread.sleep(1000); } catch(InterruptedException e){ System.out.println("The main thread interrupted"); } System.out.println("Exiting main thread"); } }
Thread Class and Runnable Interface (Contd.) • Output:
Thread Class and Runnable Interface (Contd.) • The Runnable interface is defined in the java.lang package. • The Runnable interface defines the run() method that can be overridden by a derived class. • Example: class ThreadCreator implements Runnable{ Thread t; ThreadCreator(){ t = new Thread(this, "ChildThread"); System.out.println("Child Thread:" + t); t.start(); }
Thread Class and Runnable Interface (Contd.) public void run(){ System.out.println("Child Thread Started"); System.out.println("Exiting the child thread"); } } public class RunnableTest { public static void main(String[] args) { new ThreadCreator(); System.out.println("Main thread Started");
Thread Class and Runnable Interface (Contd.) try{ Thread.sleep(5000); } catch(InterruptedException e){ System.out.println("The main thread interrupted"); } System.out.println("Exiting the main thread"); } }
Thread Class and Runnable Interface (Contd.) • Output:
Thread Priorities • The priority of a thread is an integer in the range of 1 to 10 that specifies the priority of one thread with respect to the priority of another thread. • If the processor encounters another thread with a higher priority, the current thread is pushed back and the thread with the higher priority is executed. • The next thread of a lower priority starts executing if a higher priority thread stops.
Thread Priorities (Contd.) • To set the priority of a thread, you can use the setPriority() method of the Thread class, as shown in the following code snippet: public final void setPriority(int newThreadPriority) • The priority level of a thread should be within the range of two constants, MIN_PRIORITY and MAX_PRIORITY. • You can set the priority of a thread as default by specifying the NORM_PRIORITY constant in the setPriority() method.
Thread Priorities (Contd.) • Example: class ThreadCreator implements Runnable{ Thread t; boolean runn = true; ThreadCreator(String st,int p){ t = new Thread(this,st); t.setPriority(p); t.start(); }
Thread Priorities (Contd.) public void run(){ System.out.println("Thread name : " + t.getName()); System.out.println("Thread Priority : " + t.getPriority()); } } public class ThreadPriorityTest { public static void main(String[] args) { Thread.currentThread().setPriority(Thread.MAX_PRIORI TY);
Thread Priorities (Contd.) ThreadCreator t1 = new ThreadCreator("Thread1",Thread.NORM_PRIORITY + 2); ThreadCreator t2 = new ThreadCreator("Thread2",Thread.NORM_PRIORITY - 2); System.out.println("Main Thread :" + Thread.currentThread()); System.out.println("Main Thread Priority : " + Thread.currentThread().getPriority()); } }
Thread Priorities (Contd.) • Output:
Methods of the Thread class • The java.lang.Thread class defines various methods that you can use to work with threads in a Java application. • The commonly used methods of the Thread class are: • static Thread currentThread(): Returns a reference of the currently executing thread. • String getName(): Returns the name of the thread. • int getPriority(): Returns the priority of the thread. • Thread.State getState(): Returns the state of the current thread. • boolean isAlive(): Tests if this thread is alive. • void setName(String name): Sets the name of the thread.
Methods of the Thread class (Contd.) • void setPriority(int newPriority): Changes the priority of the current thread. • static void sleep(long millis): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. • void start(): Causes this thread to begin execution; the Java Virtual Machine calls the run() method of the current thread when this method is called.
Lifecycle of a Thread • During the execution of a program, a thread may pass through various states. • These states form the lifecycle of a thread. • The various states in the lifecycle of a thread are: • New • Runnable • Not Runnable • Terminated or Dead
Lifecycle of a Thread (Contd.) • The following figure shows the lifecycle of a thread. New Runnable Dead Not Runnable start() run() method exits
Lifecycle of a Thread (Contd.) • The New Thread State: • When an instance of the Thread class is created, the thread enters the new thread state, as shown in the following code snippet: Thread demoThread = new Thread(this, “DemoName"); • When the thread is in the new state, no other method except the start() method can be called. • The Runnable Thread State: • When the start() method of a thread is invoked, the thread enters the runnable state. • The start() method allocates the system resources to the thread, schedules the thread, and passes the control to its run() method.
Lifecycle of a Thread (Contd.) • The Not Runnable Thread State: • A thread is not in the runnable state if it is: • Sleeping: A thread is put into the sleeping mode by calling the sleep() method. • Waiting: A thread can be made to wait for some specified condition to be satisfied by calling the wait() method. • Being blocked by another thread: When a thread is blocked by an I/O operation, it enters the not runnable state. • The Dead Thread State: • A thread enters the dead state when the loop in the run() method is complete. • A dead thread cannot be restarted.
Use of the sleep() and join() Methods • The java.lang.Thread class defines the sleep() and join() methods to handle the execution of threads in a Java application. • The sleep() method makes a thread pause for a specified period of time.
Use of the sleep() and join() Methods (Contd.) • Example: public class SleepTest implements Runnable{ Thread t; public void run() { for (int i = 10; i < 13; i++) { System.out.println(Thread.currentThread().getName() + " " + i); try { Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } }
Use of the sleep() and join() Methods (Contd.) public static void main(String[] args) throws Exception { Thread t = new Thread(new SleepTest()); t.start(); Thread t2 = new Thread(new SleepTest()); t2.start(); } }
Use of the sleep() and join() Methods (Contd.) • Output:
Use of the sleep() and join() Methods (Contd.) • The join() method: • Waits until the thread on which it is called, terminates. • Also enables you to specify a maximum amount of time that you need to wait for the specified thread to terminate. • Example: class ThreadCreator implements Runnable{ Thread t; ThreadCreator(){ t = new Thread(this,"ChildThread" ); System.out.println("Thread created: " + t); t.start(); }
Use of the sleep() and join() Methods (Contd.) public void run(){ try{ for(int i=1;i<4;i++) { System.out.println(t + "loop :" + i); Thread.sleep(1000); } } catch( InterruptedException obj){ System.out.println("Thread :" + t + "interrupted"); } } }
Use of the sleep() and join() Methods (Contd.) public class JoinTest { public static void main(String args[]){ ThreadCreator obj = new ThreadCreator(); System.out.println(obj.t + "is alive ? : " + obj.t.isAlive()); try{ System.out.println("Main thread waiting for child thread to finish"); obj.t.join(); }
Use of the sleep() and join() Methods (Contd.) catch(InterruptedException e) { System.out.println("Main thread is interrupted");} System.out.println(obj.t + "is alive ? : " + obj.t.isAlive()); System.out.println("Main Thread is exiting"); } }
Use of the sleep() and join() Methods (Contd.) • Output:
Synchronization • At times, you may find that more that one thread access the same set of data. • For example, in a banking application, a thread may be responsible for updating the account balance while the other thread may be responsible for displaying the total account balance. • In such a situation, the thread execution needs to be coordinated or synchronized to avoid inconsistency and deadlock.
Synchronization (Contd.) • The synchronization of threads ensures that if two or more threads need to access a shared resource then that resource is used by only one thread at a time. • You can synchronize your code by using the synchronized keyword. • You can invoke only one synchronized method for an object at any given time. • Synchronization is based on the concept of monitor. • A monitor is an object that is used as a mutually exclusive lock. • All objects and classes are associated with a monitor and only one thread can own a monitor at a given time.
Synchronization (Contd.) • When a thread is within a synchronized method, all the other threads that try to call it on the same instance have to wait. • During the execution of a synchronized method, the object is locked so that other synchronized method can not be invoked. • The monitor is automatically released when the method completes its execution. • The monitor can also be released when the synchronized method executes the wait() method. • When a thread calls the wait() method, it temporarily releases the locks that it holds.
Synchronization (Contd.) • Example: class ThreadCreator_1{ synchronized void invoke(){ System.out.println("First Statement"); try{ Thread.sleep(2000); } catch(Exception e){ System.out.println("Error " + e); } System.out.println("Second Statement"); } }
Synchronization (Contd.) class ThreadCreator_2 extends Thread{ ThreadCreator_1 t; public ThreadCreator_2(ThreadCreator_1 t){ this.t = t; } public void run(){ t.invoke(); } }
Synchronization (Contd.) public class SynchronizationTest { public static void main(String args[]){ ThreadCreator_1 obj1 = new ThreadCreator_1(); ThreadCreator_2 Obj2 = new ThreadCreator_2(obj1); ThreadCreator_2 Obj3 = new ThreadCreator_2(obj1); Obj2.start(); Obj3.start(); } }
Synchronization (Contd.) • Output:
Inter-thread Communication • A thread may notify another thread that the task has been completed. • This communication between threads is known as inter-threaded communication. • The various methods used in inter-threaded communication are: • wait(): Informs the current thread to leave its control over the monitor and sleep for a specified time until another thread calls the notify() method. • notify(): Wakes up a single thread that is waiting for the monitor of the object being executed. If multiple threads are waiting, one of them is chosen randomly. • notifyAll(): Wakes up all the threads that are waiting for the monitor of the object.
Inter-thread Communication • A thread may notify another thread that the task has been completed. • This communication between threads is known as inter-threaded communication. • The various methods used in inter-threaded communication are: • wait(): Informs the current thread to leave its control over the monitor and sleep for a specified time until another thread calls the notify() method. • notify(): Wakes up a single thread that is waiting for the monitor of the object being executed. If multiple threads are waiting, one of them is chosen randomly. • notifyAll(): Wakes up all the threads that are waiting for the monitor of the object.
Inter-thread Communication (Contd.) • Example: class ThreadCreator_1{ int testData; boolean flag = false; synchronized int getData(){ if(flag==false){ try{ wait(); } catch(InterruptedException e){ System.out.println(" Exception caught"); } }
Inter-thread Communication (Contd.) System.out.println("Got data:" + testData); flag=false; notify(); return testData; } synchronized void putData(int testData){ if(flag==true ){ try{ wait(); } catch(InterruptedException e){ System.out.println(" Exception caught"); }
Inter-thread Communication (Contd.) this.testData = testData; System.out.println("Put data with value:" + testData); flag=true; notify(); } } } class ProducerClass implements Runnable{ ThreadCreator_1 t; public ProducerClass(ThreadCreator_1 t){ this.t = t;
Inter-thread Communication (Contd.) new Thread(this,"Producer").start(); System.out.println("Put Called by producer"); } public void run(){ int data =0; while(true){ data=data+1; t.putData(data); } } }
Inter-thread Communication (Contd.) class ConsumerClass implements Runnable{ ThreadCreator_1 t; public ConsumerClass(ThreadCreator_1 t){ this.t = t; new Thread(this,"Consumer").start(); System.out.println("Get Called by consumer"); } public void run(){ while(true){ t.getData(); } } }
Inter-thread Communication (Contd.) public class ThreadCommunication { public static void main(String args[]) { ThreadCreator_1 obj1 = new ThreadCreator_1(); ProducerClass p = new ProducerClass(obj1); ConsumerClass c = new ConsumerClass(obj1); System.out.println("Press Ctrl+Shift+Del to stop"); } }
Inter-thread Communication (Contd.) • Output:
Summary • In this topic, you learn that: • Logic errors are errors that prevent the program from doing what is intended do. • Compilation errors are error that get raised when the syntax is incorrect. • Runtime errors are errors that occur during the execution of a program and disrupts the normal flow of instructions. • Checked exceptions are those exceptions for which providing exception handlers is mandatory. • Unchecked exceptions are those exception for which providing exception handlers is optional.
Summary (Contd.) • To handle exceptions Java provides try-catch-finally exceptional handler components. • The throw statement is used to explicitly throw an exception. • The throws statement is used to propagate an exception. • The try-with-resources statement ensures that each resource is closed at the end of the statement. • A custom exception can be created by creating a sub class of an existing exception class. • A thread can be defined as a path of execution in a program. • To create a thread in a Java program, you can extend the Thread class. • You can also implement the Runnable interface to create threads in a class.
Summary (Contd.) • A thread can be defined as a path of execution in a program. • To create a thread in a Java program, you can extend the Thread class. • You can also implement the Runnable interface to create threads in a class. • The Thread class defines several methods that can be overridden by a derived class. • The Runnable interface defines the run() method that can be overridden by a derived class. • The priority of a thread is an integer in the range of 1 to 10 that specifies the priority of one thread with respect to the priority of another thread. • To set the priority of a thread, you can use the setPriority() method of the Thread class.
Summary (Contd.) • When an instance of the Thread class is created, the thread enters the new thread state. • When the start() method of a thread is invoked, the thread enters the runnable state. • A thread enters the dead state when the loop in the run() method is complete. • A dead thread cannot be restarted. • The synchronization of threads ensures that if two or more threads need to access a shared resource then that resource is used by only one thread at a time. • A thread may notify another thread that the task has been completed. • The communication between threads is known as inter-threaded communication.

Java Day-5

  • 1.
    © People Strategists- Duplication is strictly prohibited - www.peoplestrategists.com 1
  • 2.
  • 3.
  • 4.
    Errors and Exception •A programmer can make following types of error in the program: • Logical errors • Compilation errors • Runtime errors • Logic errors are errors that prevent the program from doing what is intended do. • If a program has logical errors, the code may compile and run without error, but the result of an operation may not produce a expected result. • Compilation errors are error that get raised when the syntax is incorrect.
  • 5.
    Errors and Exception(Contd.) • Compilation errors prevent the program from compiling. • Runtime errors are errors that occur during the execution of a program and disrupts the normal flow of instructions. • Runtime errors occur when your program attempts an operation that is impossible to carry out. • Runtime error also called as exception. • The logical errors and compilation errors can be rectified. • Runtime errors should be handled by the program.
  • 6.
    Errors and Exception(Contd.) • To work with exception Java provide various classes: java.lang.Throwable java.lang.Error java.lang.NoClassDefFoundError java.lang.VirtualMachineError java.lang.Exception java.lang.RuntimeException java.lang.ArithmeticException java.lang.IndexOutOfBoundsException java.io.IOException java.io.FileNotFoundException
  • 7.
    Errors and Exception(Contd.) • The Throwable class is the base class for all exception classes. • The Exception and Error classes are two sub classes for Throwable. • The sub classes of Error class represents an unusual situations, such as JVM running out of memory. These type of errors are not usually caused by the program errors. • The sub classes of Exception class represents program errors or errors raised because a some resource is not available, such as the file to be accesses is not available.
  • 8.
    Errors and Exception(Contd.) • The RuntimeException is a sub class of Exception class. • The RuntimeException and its sub classes represent errors that may be raised to due to program error. For example, dividing a number by zero and accessing an array element outside the range of array.
  • 9.
    Checked and UncheckedException • Checked exceptions are those exceptions for which providing exception handlers is mandatory. • Checked exceptions should be either caught or be declared to be thrown. • Unchecked exceptions are those exception for which providing exception handlers is optional. • All exceptions of type RunTimeException or its subclasses are unchecked Exceptions.
  • 10.
    Handling Exceptions • Tohandle exceptions Java provides following exceptional handler components: • try block • catch block • finally block • The structure of exception handler component is: try { } catch (ExceptionType name) { } catch (ExceptionType name) { } finally{ }
  • 11.
    Handling Exceptions (Contd.) •The code that might throw an exception, should be added inside the try block. • The catch block is an exception handler that handles the type of exception indicated by its argument. • The finally block always gets executed irrespective of an exception raised. • Therefore, a finally block can be used to perform clean up operations, such as closing a file or releasing a network socket. • A try block can be associated with one or more catch blocks and one finally block.
  • 12.
    Handling Exceptions (Contd.) •An example to handle unchecked exception: public class ExceptionDemo { public static void main(String args[]){ try{ int c=10/0; System.out.println("Value="+c); }catch(ArithmeticException e){ System.out.println("Catch Block:"+e); } finally{ System.out.println("finally block"); } } }
  • 13.
    Handling Exceptions (Contd.) •The preceding code output will be: Catch Block:java.lang.ArithmeticException: / by zero finally block • In the preceding code, if the statement, int c=10/0;, is modified to int c=10/1;, then the output will be: Value=10 finally block
  • 14.
    Handling Exceptions (Contd.) •In the preceding code, the catch block can be modified as shown in the following code snippet: catch(ArithmeticException e){ System.out.println("Catch 1:"+e); e.printStackTrace(); } • Here, printStackTrace() method will print the stack trace from where the exception occurred. The output after modifying the code will be: Catch Block:java.lang.ArithmeticException: / by zero finally block java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:4)
  • 15.
    Handling Exceptions (Contd.) •An example to handle unchecked exception with multiple catch blocks: public class ExceptionDemo { public static void main(String args[]){ try{ String s=new String("10"); int i=new Integer(s); int c=i/0; System.out.println("Value="+c); }
  • 16.
    Handling Exceptions (Contd.) catch(ArithmeticExceptione){ System.out.println("Catch 1:"+e); }catch(RuntimeException e){ System.out.println("Catch 2:"+e); } finally{ System.out.println("finally block"); } } }
  • 17.
    Handling Exceptions (Contd.) •The preceding code output will be: Catch 1:java.lang.ArithmeticException: / by zero finally block • In the preceding code, if the statement, String s=new String("10");, is modified to String s=new String("hello");. Then, the output will be: Catch 2:java.lang.NumberFormatException: For input string: "hello" finally block
  • 18.
    Handling Exceptions (Contd.) •Consider the following code: public class ExceptionDemo { public static void main(String args[]){ try{ int c=10/0; System.out.println("Value="+c); }catch(RuntimeException e){ System.out.println(e); } catch(ArithmeticException e){ System.out.println(e); } finally{ System.out.println("finally block"); } } }
  • 19.
    Handling Exceptions (Contd.) •The preceding code will generate a compilation error because the handler of the most specific type should always be placed before the general exception type.
  • 20.
    Handling Exceptions (Contd.) •Consider the following code: public class ExceptionDemo { static void divide(){ try{ String s=new String("10"); int i=new Integer(s); int c=i/0; System.out.println("Value="+c); }catch(ArithmeticException e){ System.out.println(e); } finally{ System.out.println("Sub finally block"); } }
  • 21.
    Handling Exceptions (Contd.) publicstatic void main(String args[]){ try{ divide(); } catch(RuntimeException e){ System.out.println(e); } finally{ System.out.println("Main finally block"); } } }
  • 22.
    Handling Exceptions (Contd.) •The preceding code output will be: java.lang.ArithmeticException: / by zero Sub finally block Main finally block • In the preceding code, the statement, String s=new String("10");, is modified to String s=new String(“java");, the output will be: Sub finally block java.lang.NumberFormatException: For input string: "java" Main finally block
  • 23.
    Multi Catch • InJava 7 and later versions, a single catch can handle multiple types of exception. • The multi catch feature reduce codes duplication. • The multi catch syntax: try { } catch(<ExceptionType name> | <ExceptionType name> <reference name>) { }
  • 24.
    Multi Catch (Contd.) •An example to work with multi catch public class Test { public static void main(String args[]){ int divident[]={10,2,5,20,45}; int divisor[]={0,1,2}; try{ int q=divident[1]/divisor[3]; System.out.println("Value="+q); }
  • 25.
    Multi Catch (Contd.) •catch(ArithmeticException | ArrayIndexOutOfBoundsException e){ System.out.println(e); }catch(RuntimeException e){ System.out.println(e); } finally{ System.out.println("finally1"); } } }
  • 26.
    Multi Catch (Contd.) •The preceding code output: java.lang.ArrayIndexOutOfBoundsException:3 finally1 • In the preceding code, if the statement, int q=divident[1]/divisor[3];, is modified to int q=divident[1]/divisor[0];, then the code will generate following output: java.lang.ArithmeticException: / by zero finally1
  • 27.
    Use of throwand throws • The throw statement is used to explicitly throw an exception. • The throw statement requires an argument of a Throwable object. • The throw statement can be used within the method, catch block, or finally block. • The throws statement is used to propagate an exception. • The throws statement is used with the method signature.
  • 28.
    Use of throwand throws (Contd.) • An example to work with throw statement: class ThrowDemo{ public static void main(String args[]) { try { int age=12; if(age <= 18) throw new ArithmeticException(); else System.out.println("Eligible for voting"); } catch(ArithmeticException e) { System.out.println("U r not eligible for voting: "+e); } } }
  • 29.
    Use of throwand throws (Contd.) • The preceding code output will be: U r not eligible for voting: java.lang.ArithmeticException
  • 30.
    Use of throwand throws (Contd.) • An example to re-throw an exception: import java.io.*; class ThrowDemo{ static void check(){ try { int age=12; if(age <= 18) throw new ArithmeticException(); else System.out.println("Eligible for voting"); } catch(ArithmeticException e) { System.out.println("U r not eligible for voting: "+e); throw e; } }
  • 31.
    Use of throwand throws (Contd.) public static void main(String args[]){ try{ check(); System.out.println("After the check() call"); } catch(RuntimeException e) { System.out.println("Main Catch "+e); } } }
  • 32.
    Use of throwand throws (Contd.) • The preceding code output will be: U r not eligible for voting: java.lang.ArithmeticException Main Catch java.lang.ArithmeticException
  • 33.
    Use of throwand throws (Contd.) • Consider the following code snippet: import java.io.*; class ThrowsDemo { public static void main(String args[]){ FileInputStream fis = null; fis = new FileInputStream("abc.txt"); fis.close(); } } • The preceding code will generate compilation errors because the code would raise an exception, java.io.FileNotFoundException, if the text file is not found.
  • 34.
    Use of throwand throws (Contd.) • The exception, java.io.FileNotFoundException is a checked exception. • Therefore, it must be declared as an exception that may be thrown by the method. • In the preceding code, main method should be modified as shown in the following code snippet: public static void main(String args[])throws IOException{ • The throws statement is used to declare an exception that may be thrown by the method.
  • 35.
    Use of throwand throws (Contd.) • Consider the following code snippet: class Base{ void print() throws ArithmeticException{ System.out.println("Base Print"); } } class Sub extends Base{ void print() throws Exception{ System.out.println("Sub Print"); } }
  • 36.
    Use of throwand throws (Contd.) • The preceding code will raise a compilation error because the overridden method is throwing a broader exception. • While declaring exceptions in overridden methods, the overridden method can reduce or eliminate the exception declaration. However, the overridden methods must not throw a new or broader checked exception. • The throws statement can be used to declare multiple exception as shown in the following code snippet: void print() throws Exception,RuntimeException{ System.out.println("Base Print"); }
  • 37.
    Automatic Resource Managementin Java7 • The try-with-resources statement is a try statement that declares one or more resources. • A resource is an object that must be closed after the program is finished with it. • The try-with-resources statement ensures that each resource is closed at the end of the statement. • Any object that implements java.lang.AutoCloseable can be used as a resource in try-with-resources statement .
  • 38.
    Automatic Resource Managementin Java7 • An example code snippet to use try-with-resource statement: try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } • In the preceding code snippet, the BufferedReader class instance is declared in a try-with-resource statement. This will ensure the connection is closed regardless of whether the try statement completes normally or abruptly.
  • 39.
    Create Custom Exceptions •Java allows to create a custom exceptions, if an exception type is not represented by Java platform. • A custom exception can be created by creating a sub class of an existing exception class.
  • 40.
    Create Custom Exceptions(Contd.) • An example to work with custom exception: public class CustomException extends Exception { public CustomException() { System.out.println("CustomException"); } public CustomException(String message) { super(message); } }
  • 41.
    Create Custom Exceptions(Contd.) public class CustomExceptionTest { public static void main(String[] args) { try { testException(null); } catch (CustomException e) { e.printStackTrace(); } } public static void testException(String string) throws CustomException { if(string == null) throw new CustomException("The String value is null"); } }
  • 42.
    Create Custom Exceptions(Contd.) • The preceding code output will be: CustomException: The String value is null at CustomExceptionTest.testException(CustomExceptionTest. java:18) at CustomExceptionTest.main(CustomExceptionTest.java:7)
  • 43.
  • 44.
    Introduction to Threads •A thread can be defined as a path of execution in a program. In other words, a thread is a single sequential flow of control within a program. • Example: • When you are performing multiple tasks on a computer, such as listening to music, writing a document, printing another document, and installing a software, each of these tasks are performed as a single thread by the CPU. Thread 1 Thread 2 Thread 3 Thread 4 Playing Music Writing Document Printing Document Installing Software
  • 45.
    Thread Class andRunnable Interface • In a Java program, you can create multiple paths of execution by creating threads. • To create a thread in a Java program, you can extend the Thread class. • However, if a class in which you need to create a thread already extends another class, you cannot extend the Thread class to create threads as Java does not support multiple inheritance. • The alternate is to implement the Runnable interface to create threads in the class.
  • 46.
    Thread Class andRunnable Interface (Contd.) • The Thread class is defined in the java.lang package. • The Thread class defines several methods that can be overridden by a derived class. • Example: class ThreadCreator extends Thread{ ThreadCreator(){ super("ChildThread"); // Creates new thread System.out.println("ChildThread:" + this); start(); }
  • 47.
    Thread Class andRunnable Interface (Contd.) public void run(){ System.out.println("The child thread started"); System.out.println("Exiting the child thread"); }} public class ThreadTest { public static void main(String[] args){ new ThreadCreator(); System.out.println("The main thread started"); System.out.println("The main thread sleeping");
  • 48.
    Thread Class andRunnable Interface (Contd.) try{ Thread.sleep(1000); } catch(InterruptedException e){ System.out.println("The main thread interrupted"); } System.out.println("Exiting main thread"); } }
  • 49.
    Thread Class andRunnable Interface (Contd.) • Output:
  • 50.
    Thread Class andRunnable Interface (Contd.) • The Runnable interface is defined in the java.lang package. • The Runnable interface defines the run() method that can be overridden by a derived class. • Example: class ThreadCreator implements Runnable{ Thread t; ThreadCreator(){ t = new Thread(this, "ChildThread"); System.out.println("Child Thread:" + t); t.start(); }
  • 51.
    Thread Class andRunnable Interface (Contd.) public void run(){ System.out.println("Child Thread Started"); System.out.println("Exiting the child thread"); } } public class RunnableTest { public static void main(String[] args) { new ThreadCreator(); System.out.println("Main thread Started");
  • 52.
    Thread Class andRunnable Interface (Contd.) try{ Thread.sleep(5000); } catch(InterruptedException e){ System.out.println("The main thread interrupted"); } System.out.println("Exiting the main thread"); } }
  • 53.
    Thread Class andRunnable Interface (Contd.) • Output:
  • 54.
    Thread Priorities • Thepriority of a thread is an integer in the range of 1 to 10 that specifies the priority of one thread with respect to the priority of another thread. • If the processor encounters another thread with a higher priority, the current thread is pushed back and the thread with the higher priority is executed. • The next thread of a lower priority starts executing if a higher priority thread stops.
  • 55.
    Thread Priorities (Contd.) •To set the priority of a thread, you can use the setPriority() method of the Thread class, as shown in the following code snippet: public final void setPriority(int newThreadPriority) • The priority level of a thread should be within the range of two constants, MIN_PRIORITY and MAX_PRIORITY. • You can set the priority of a thread as default by specifying the NORM_PRIORITY constant in the setPriority() method.
  • 56.
    Thread Priorities (Contd.) •Example: class ThreadCreator implements Runnable{ Thread t; boolean runn = true; ThreadCreator(String st,int p){ t = new Thread(this,st); t.setPriority(p); t.start(); }
  • 57.
    Thread Priorities (Contd.) publicvoid run(){ System.out.println("Thread name : " + t.getName()); System.out.println("Thread Priority : " + t.getPriority()); } } public class ThreadPriorityTest { public static void main(String[] args) { Thread.currentThread().setPriority(Thread.MAX_PRIORI TY);
  • 58.
    Thread Priorities (Contd.) ThreadCreatort1 = new ThreadCreator("Thread1",Thread.NORM_PRIORITY + 2); ThreadCreator t2 = new ThreadCreator("Thread2",Thread.NORM_PRIORITY - 2); System.out.println("Main Thread :" + Thread.currentThread()); System.out.println("Main Thread Priority : " + Thread.currentThread().getPriority()); } }
  • 59.
  • 60.
    Methods of theThread class • The java.lang.Thread class defines various methods that you can use to work with threads in a Java application. • The commonly used methods of the Thread class are: • static Thread currentThread(): Returns a reference of the currently executing thread. • String getName(): Returns the name of the thread. • int getPriority(): Returns the priority of the thread. • Thread.State getState(): Returns the state of the current thread. • boolean isAlive(): Tests if this thread is alive. • void setName(String name): Sets the name of the thread.
  • 61.
    Methods of theThread class (Contd.) • void setPriority(int newPriority): Changes the priority of the current thread. • static void sleep(long millis): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. • void start(): Causes this thread to begin execution; the Java Virtual Machine calls the run() method of the current thread when this method is called.
  • 62.
    Lifecycle of aThread • During the execution of a program, a thread may pass through various states. • These states form the lifecycle of a thread. • The various states in the lifecycle of a thread are: • New • Runnable • Not Runnable • Terminated or Dead
  • 63.
    Lifecycle of aThread (Contd.) • The following figure shows the lifecycle of a thread. New Runnable Dead Not Runnable start() run() method exits
  • 64.
    Lifecycle of aThread (Contd.) • The New Thread State: • When an instance of the Thread class is created, the thread enters the new thread state, as shown in the following code snippet: Thread demoThread = new Thread(this, “DemoName"); • When the thread is in the new state, no other method except the start() method can be called. • The Runnable Thread State: • When the start() method of a thread is invoked, the thread enters the runnable state. • The start() method allocates the system resources to the thread, schedules the thread, and passes the control to its run() method.
  • 65.
    Lifecycle of aThread (Contd.) • The Not Runnable Thread State: • A thread is not in the runnable state if it is: • Sleeping: A thread is put into the sleeping mode by calling the sleep() method. • Waiting: A thread can be made to wait for some specified condition to be satisfied by calling the wait() method. • Being blocked by another thread: When a thread is blocked by an I/O operation, it enters the not runnable state. • The Dead Thread State: • A thread enters the dead state when the loop in the run() method is complete. • A dead thread cannot be restarted.
  • 66.
    Use of thesleep() and join() Methods • The java.lang.Thread class defines the sleep() and join() methods to handle the execution of threads in a Java application. • The sleep() method makes a thread pause for a specified period of time.
  • 67.
    Use of thesleep() and join() Methods (Contd.) • Example: public class SleepTest implements Runnable{ Thread t; public void run() { for (int i = 10; i < 13; i++) { System.out.println(Thread.currentThread().getName() + " " + i); try { Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } }
  • 68.
    Use of thesleep() and join() Methods (Contd.) public static void main(String[] args) throws Exception { Thread t = new Thread(new SleepTest()); t.start(); Thread t2 = new Thread(new SleepTest()); t2.start(); } }
  • 69.
    Use of thesleep() and join() Methods (Contd.) • Output:
  • 70.
    Use of thesleep() and join() Methods (Contd.) • The join() method: • Waits until the thread on which it is called, terminates. • Also enables you to specify a maximum amount of time that you need to wait for the specified thread to terminate. • Example: class ThreadCreator implements Runnable{ Thread t; ThreadCreator(){ t = new Thread(this,"ChildThread" ); System.out.println("Thread created: " + t); t.start(); }
  • 71.
    Use of thesleep() and join() Methods (Contd.) public void run(){ try{ for(int i=1;i<4;i++) { System.out.println(t + "loop :" + i); Thread.sleep(1000); } } catch( InterruptedException obj){ System.out.println("Thread :" + t + "interrupted"); } } }
  • 72.
    Use of thesleep() and join() Methods (Contd.) public class JoinTest { public static void main(String args[]){ ThreadCreator obj = new ThreadCreator(); System.out.println(obj.t + "is alive ? : " + obj.t.isAlive()); try{ System.out.println("Main thread waiting for child thread to finish"); obj.t.join(); }
  • 73.
    Use of thesleep() and join() Methods (Contd.) catch(InterruptedException e) { System.out.println("Main thread is interrupted");} System.out.println(obj.t + "is alive ? : " + obj.t.isAlive()); System.out.println("Main Thread is exiting"); } }
  • 74.
    Use of thesleep() and join() Methods (Contd.) • Output:
  • 75.
    Synchronization • At times,you may find that more that one thread access the same set of data. • For example, in a banking application, a thread may be responsible for updating the account balance while the other thread may be responsible for displaying the total account balance. • In such a situation, the thread execution needs to be coordinated or synchronized to avoid inconsistency and deadlock.
  • 76.
    Synchronization (Contd.) • Thesynchronization of threads ensures that if two or more threads need to access a shared resource then that resource is used by only one thread at a time. • You can synchronize your code by using the synchronized keyword. • You can invoke only one synchronized method for an object at any given time. • Synchronization is based on the concept of monitor. • A monitor is an object that is used as a mutually exclusive lock. • All objects and classes are associated with a monitor and only one thread can own a monitor at a given time.
  • 77.
    Synchronization (Contd.) • Whena thread is within a synchronized method, all the other threads that try to call it on the same instance have to wait. • During the execution of a synchronized method, the object is locked so that other synchronized method can not be invoked. • The monitor is automatically released when the method completes its execution. • The monitor can also be released when the synchronized method executes the wait() method. • When a thread calls the wait() method, it temporarily releases the locks that it holds.
  • 78.
    Synchronization (Contd.) • Example: classThreadCreator_1{ synchronized void invoke(){ System.out.println("First Statement"); try{ Thread.sleep(2000); } catch(Exception e){ System.out.println("Error " + e); } System.out.println("Second Statement"); } }
  • 79.
    Synchronization (Contd.) class ThreadCreator_2extends Thread{ ThreadCreator_1 t; public ThreadCreator_2(ThreadCreator_1 t){ this.t = t; } public void run(){ t.invoke(); } }
  • 80.
    Synchronization (Contd.) public classSynchronizationTest { public static void main(String args[]){ ThreadCreator_1 obj1 = new ThreadCreator_1(); ThreadCreator_2 Obj2 = new ThreadCreator_2(obj1); ThreadCreator_2 Obj3 = new ThreadCreator_2(obj1); Obj2.start(); Obj3.start(); } }
  • 81.
  • 82.
    Inter-thread Communication • Athread may notify another thread that the task has been completed. • This communication between threads is known as inter-threaded communication. • The various methods used in inter-threaded communication are: • wait(): Informs the current thread to leave its control over the monitor and sleep for a specified time until another thread calls the notify() method. • notify(): Wakes up a single thread that is waiting for the monitor of the object being executed. If multiple threads are waiting, one of them is chosen randomly. • notifyAll(): Wakes up all the threads that are waiting for the monitor of the object.
  • 83.
    Inter-thread Communication • Athread may notify another thread that the task has been completed. • This communication between threads is known as inter-threaded communication. • The various methods used in inter-threaded communication are: • wait(): Informs the current thread to leave its control over the monitor and sleep for a specified time until another thread calls the notify() method. • notify(): Wakes up a single thread that is waiting for the monitor of the object being executed. If multiple threads are waiting, one of them is chosen randomly. • notifyAll(): Wakes up all the threads that are waiting for the monitor of the object.
  • 84.
    Inter-thread Communication (Contd.) •Example: class ThreadCreator_1{ int testData; boolean flag = false; synchronized int getData(){ if(flag==false){ try{ wait(); } catch(InterruptedException e){ System.out.println(" Exception caught"); } }
  • 85.
    Inter-thread Communication (Contd.) System.out.println("Gotdata:" + testData); flag=false; notify(); return testData; } synchronized void putData(int testData){ if(flag==true ){ try{ wait(); } catch(InterruptedException e){ System.out.println(" Exception caught"); }
  • 86.
    Inter-thread Communication (Contd.) this.testData= testData; System.out.println("Put data with value:" + testData); flag=true; notify(); } } } class ProducerClass implements Runnable{ ThreadCreator_1 t; public ProducerClass(ThreadCreator_1 t){ this.t = t;
  • 87.
    Inter-thread Communication (Contd.) newThread(this,"Producer").start(); System.out.println("Put Called by producer"); } public void run(){ int data =0; while(true){ data=data+1; t.putData(data); } } }
  • 88.
    Inter-thread Communication (Contd.) classConsumerClass implements Runnable{ ThreadCreator_1 t; public ConsumerClass(ThreadCreator_1 t){ this.t = t; new Thread(this,"Consumer").start(); System.out.println("Get Called by consumer"); } public void run(){ while(true){ t.getData(); } } }
  • 89.
    Inter-thread Communication (Contd.) publicclass ThreadCommunication { public static void main(String args[]) { ThreadCreator_1 obj1 = new ThreadCreator_1(); ProducerClass p = new ProducerClass(obj1); ConsumerClass c = new ConsumerClass(obj1); System.out.println("Press Ctrl+Shift+Del to stop"); } }
  • 90.
  • 91.
    Summary • In thistopic, you learn that: • Logic errors are errors that prevent the program from doing what is intended do. • Compilation errors are error that get raised when the syntax is incorrect. • Runtime errors are errors that occur during the execution of a program and disrupts the normal flow of instructions. • Checked exceptions are those exceptions for which providing exception handlers is mandatory. • Unchecked exceptions are those exception for which providing exception handlers is optional.
  • 92.
    Summary (Contd.) • Tohandle exceptions Java provides try-catch-finally exceptional handler components. • The throw statement is used to explicitly throw an exception. • The throws statement is used to propagate an exception. • The try-with-resources statement ensures that each resource is closed at the end of the statement. • A custom exception can be created by creating a sub class of an existing exception class. • A thread can be defined as a path of execution in a program. • To create a thread in a Java program, you can extend the Thread class. • You can also implement the Runnable interface to create threads in a class.
  • 93.
    Summary (Contd.) • Athread can be defined as a path of execution in a program. • To create a thread in a Java program, you can extend the Thread class. • You can also implement the Runnable interface to create threads in a class. • The Thread class defines several methods that can be overridden by a derived class. • The Runnable interface defines the run() method that can be overridden by a derived class. • The priority of a thread is an integer in the range of 1 to 10 that specifies the priority of one thread with respect to the priority of another thread. • To set the priority of a thread, you can use the setPriority() method of the Thread class.
  • 94.
    Summary (Contd.) • Whenan instance of the Thread class is created, the thread enters the new thread state. • When the start() method of a thread is invoked, the thread enters the runnable state. • A thread enters the dead state when the loop in the run() method is complete. • A dead thread cannot be restarted. • The synchronization of threads ensures that if two or more threads need to access a shared resource then that resource is used by only one thread at a time. • A thread may notify another thread that the task has been completed. • The communication between threads is known as inter-threaded communication.