Java Day-5

94
© People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1

Transcript of Java Day-5

Page 1: Java Day-5

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com

1

Page 2: Java Day-5

Day 5Exception Handling

Threads

Page 3: Java Day-5

Exception Handling

Page 4: Java Day-5

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 isintended do.

• If a program has logical errors, the code may compile and run withouterror, but the result of an operation may not produce a expectedresult.

• Compilation errors are error that get raised when the syntax isincorrect.

Page 5: Java Day-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.

Page 6: Java Day-5

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

Page 7: Java Day-5

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 usuallycaused by the program errors.

• The sub classes of Exception class represents program errors or errorsraised because a some resource is not available, such as the file to beaccesses is not available.

Page 8: Java Day-5

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 byzero and accessing an array element outside the range of array.

Page 9: Java Day-5

Checked and Unchecked Exception

• Checked exceptions are those exceptions for which providingexception handlers is mandatory.

• Checked exceptions should be either caught or be declared to bethrown.

• Unchecked exceptions are those exception for which providingexception handlers is optional.

• All exceptions of type RunTimeException or its subclasses areunchecked Exceptions.

Page 10: Java Day-5

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{}

Page 11: Java Day-5

Handling Exceptions (Contd.)

• The code that might throw an exception, should be added inside thetry block.

• The catch block is an exception handler that handles the type ofexception indicated by its argument.

• The finally block always gets executed irrespective of an exceptionraised.

• 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 onefinally block.

Page 12: Java Day-5

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");

}

}

}

Page 13: Java Day-5

Handling Exceptions (Contd.)

• The preceding code output will be:Catch Block:java.lang.ArithmeticException: / by zerofinally block

• In the preceding code, if the statement, int c=10/0;, is modified to intc=10/1;, then the output will be:Value=10finally block

Page 14: Java Day-5

Handling Exceptions (Contd.)

• In the preceding code, the catch block can be modified as shown inthe following code snippet:catch(ArithmeticException e){

System.out.println("Catch 1:"+e);e.printStackTrace();

}

• Here, printStackTrace() method will print the stack trace from wherethe exception occurred. The output after modifying the code will be:Catch Block:java.lang.ArithmeticException: / by zerofinally blockjava.lang.ArithmeticException: / by zero

at ExceptionDemo.main(ExceptionDemo.java:4)

Page 15: Java Day-5

Handling Exceptions (Contd.)

• An example to handle unchecked exception with multiple catchblocks: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);

}

Page 16: Java Day-5

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");

}}

}

Page 17: Java Day-5

Handling Exceptions (Contd.)

• The preceding code output will be:Catch 1:java.lang.ArithmeticException: / by zerofinally block

• In the preceding code, if the statement, String s=new String("10");, ismodified to String s=new String("hello");. Then, the output will be:

Catch 2:java.lang.NumberFormatException: Forinput string: "hello"

finally block

Page 18: Java Day-5

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");}

}}

Page 19: Java Day-5

Handling Exceptions (Contd.)

• The preceding code will generate a compilation error because thehandler of the most specific type should always be placed before thegeneral exception type.

Page 20: Java Day-5

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");}

}

Page 21: Java Day-5

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");}

}}

Page 22: Java Day-5

Handling Exceptions (Contd.)

• The preceding code output will be:java.lang.ArithmeticException: / by zeroSub finally blockMain finally block

• In the preceding code, the statement, String s=new String("10");, ismodified to String s=new String(“java");, the output will be:Sub finally blockjava.lang.NumberFormatException: For input string:"java"Main finally block

Page 23: Java Day-5

Multi Catch

• In Java 7 and later versions, a single catch can handle multiple typesof exception.

• The multi catch feature reduce codes duplication.• The multi catch syntax:

try {} catch(<ExceptionType name> | <ExceptionType name><reference name>) {

}

Page 24: Java Day-5

Multi Catch (Contd.)

• An example to work with multi catchpublic 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);

}

Page 25: Java Day-5

Multi Catch (Contd.)

• catch(ArithmeticException | ArrayIndexOutOfBoundsException e){

System.out.println(e);

}catch(RuntimeException e){

System.out.println(e);

}

finally{

System.out.println("finally1");

}

}

}

Page 26: Java Day-5

Multi Catch (Contd.)

• The preceding code output:java.lang.ArrayIndexOutOfBoundsException:3finally1

• In the preceding code, if the statement, int q=divident[1]/divisor[3];, ismodified to int q=divident[1]/divisor[0];, then the code will generatefollowing output:java.lang.ArithmeticException: / by zero

finally1

Page 27: Java Day-5

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.

Page 28: Java Day-5

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);

}}

}

Page 29: Java Day-5

Use of throw and throws (Contd.)

• The preceding code output will be:U r not eligible for voting:java.lang.ArithmeticException

Page 30: Java Day-5

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;

}}

Page 31: Java Day-5

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);

}}

}

Page 32: Java Day-5

Use of throw and throws (Contd.)

• The preceding code output will be:U r not eligible for voting:java.lang.ArithmeticExceptionMain Catch java.lang.ArithmeticException

Page 33: Java Day-5

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 thecode would raise an exception, java.io.FileNotFoundException, if thetext file is not found.

Page 34: Java Day-5

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[])throwsIOException{

• The throws statement is used to declare an exception that may bethrown by the method.

Page 35: Java Day-5

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");

}}

Page 36: Java Day-5

Use of throw and throws (Contd.)

• The preceding code will raise a compilation error because theoverridden method is throwing a broader exception.

• While declaring exceptions in overridden methods, the overriddenmethod can reduce or eliminate the exception declaration. However,the overridden methods must not throw a new or broader checkedexception.

• The throws statement can be used to declare multiple exception asshown in the following code snippet:void print() throws Exception,RuntimeException{

System.out.println("Base Print");}

Page 37: Java Day-5

Automatic Resource Management in Java7

• The try-with-resources statement is a try statement that declares oneor more resources.

• A resource is an object that must be closed after the program isfinished with it.

• The try-with-resources statement ensures that each resource isclosed at the end of the statement.

• Any object that implements java.lang.AutoCloseable can be used as aresource in try-with-resources statement .

Page 38: Java Day-5

Automatic Resource Management in Java7

• An example code snippet to use try-with-resource statement:try (BufferedReader br =

new BufferedReader(newFileReader(path))) {

return br.readLine();}

• In the preceding code snippet, the BufferedReader class instance isdeclared in a try-with-resource statement. This will ensure theconnection is closed regardless of whether the try statementcompletes normally or abruptly.

Page 39: Java Day-5

Create Custom Exceptions

• Java allows to create a custom exceptions, if an exception type is notrepresented by Java platform.

• A custom exception can be created by creating a sub class of anexisting exception class.

Page 40: Java Day-5

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);}

}

Page 41: Java Day-5

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");

}}

Page 42: Java Day-5

Create Custom Exceptions (Contd.)

• The preceding code output will be:CustomException: The String value is null

atCustomExceptionTest.testException(CustomExceptionTest.java:18)

atCustomExceptionTest.main(CustomExceptionTest.java:7)

Page 43: Java Day-5

Threads

Page 44: Java Day-5

Introduction to Threads

• A thread can be defined as a path of execution in a program. In otherwords, a thread is a single sequential flow of control within aprogram.

• Example:• When you are performing multiple tasks on a computer, such as listening to

music, writing a document, printing another document, and installing asoftware, each of these tasks are performed as a single thread by the CPU.

Thread 1Thread 2Thread 3Thread 4

Playing MusicWriting DocumentPrinting DocumentInstalling Software

Page 45: Java Day-5

Thread Class and Runnable Interface

• In a Java program, you can create multiple paths of execution bycreating threads.

• To create a thread in a Java program, you can extend the Threadclass.

• However, if a class in which you need to create a thread alreadyextends another class, you cannot extend the Thread class to createthreads as Java does not support multiple inheritance.

• The alternate is to implement the Runnable interface to createthreads in the class.

Page 46: Java Day-5

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 threadSystem.out.println("ChildThread:" + this);start();

}

Page 47: Java Day-5

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");

Page 48: Java Day-5

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");}}

Page 49: Java Day-5

Thread Class and Runnable Interface (Contd.)

• Output:

Page 50: Java Day-5

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();

}

Page 51: Java Day-5

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");

Page 52: Java Day-5

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");}}

Page 53: Java Day-5

Thread Class and Runnable Interface (Contd.)

• Output:

Page 54: Java Day-5

Thread Priorities

• The priority of a thread is an integer in the range of 1 to 10 thatspecifies the priority of one thread with respect to the priority ofanother thread.

• If the processor encounters another thread with a higher priority, thecurrent thread is pushed back and the thread with the higher priorityis executed.

• The next thread of a lower priority starts executing if a higher prioritythread stops.

Page 55: Java Day-5

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 twoconstants, MIN_PRIORITY and MAX_PRIORITY.

• You can set the priority of a thread as default by specifying theNORM_PRIORITY constant in the setPriority() method.

Page 56: Java Day-5

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();}

Page 57: Java Day-5

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_PRIORITY);

Page 58: Java Day-5

Thread Priorities (Contd.)

ThreadCreator t1 = newThreadCreator("Thread1",Thread.NORM_PRIORITY + 2);ThreadCreator t2 = newThreadCreator("Thread2",Thread.NORM_PRIORITY - 2);System.out.println("Main Thread :" +Thread.currentThread());

System.out.println("Main Thread Priority : " +Thread.currentThread().getPriority());}}

Page 59: Java Day-5

Thread Priorities (Contd.)

• Output:

Page 60: Java Day-5

Methods of the Thread class

• The java.lang.Thread class defines various methods that youcan 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.

Page 61: Java Day-5

Methods of the Thread class (Contd.)

• void setPriority(int newPriority): Changes the priority of thecurrent thread.

• static void sleep(long millis): Causes the currently executingthread to sleep (temporarily cease execution) for the specified number ofmilliseconds.

• void start(): Causes this thread to begin execution; the Java VirtualMachine calls the run() method of the current thread when this method iscalled.

Page 62: Java Day-5

Lifecycle of a Thread

• During the execution of a program, a thread may pass through variousstates.

• 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

Page 63: Java Day-5

Lifecycle of a Thread (Contd.)

• The following figure shows the lifecycle of a thread.

New

Runnable

Dead

NotRunnable

start()

run() methodexits

Page 64: Java Day-5

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.

Page 65: Java Day-5

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.

Page 66: Java Day-5

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 oftime.

Page 67: Java Day-5

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);

}}}

Page 68: Java Day-5

Use of the sleep() and join() Methods (Contd.)

public static void main(String[] args) throwsException {Thread t = new Thread(new SleepTest());t.start();Thread t2 = new Thread(new SleepTest());t2.start();}

}

Page 69: Java Day-5

Use of the sleep() and join() Methods (Contd.)

• Output:

Page 70: Java Day-5

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();}

Page 71: Java Day-5

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");}

}}

Page 72: Java Day-5

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 forchild thread to finish");obj.t.join();

}

Page 73: Java Day-5

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");

}}

Page 74: Java Day-5

Use of the sleep() and join() Methods (Contd.)

• Output:

Page 75: Java Day-5

Synchronization

• At times, you may find that more that one thread access the same setof data.

• For example, in a banking application, a thread may be responsiblefor updating the account balance while the other thread may beresponsible for displaying the total account balance.

• In such a situation, the thread execution needs to be coordinated orsynchronized to avoid inconsistency and deadlock.

Page 76: Java Day-5

Synchronization (Contd.)

• The synchronization of threads ensures that if two or more threadsneed to access a shared resource then that resource is used by onlyone thread at a time.

• You can synchronize your code by using the synchronizedkeyword.

• You can invoke only one synchronized method for an object at anygiven 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.

Page 77: Java Day-5

Synchronization (Contd.)

• When a thread is within a synchronized method, all the other threadsthat try to call it on the same instance have to wait.

• During the execution of a synchronized method, the object is lockedso that other synchronized method can not be invoked.

• The monitor is automatically released when the method completes itsexecution.

• The monitor can also be released when the synchronized methodexecutes the wait() method.

• When a thread calls the wait()method, it temporarily releases thelocks that it holds.

Page 78: Java Day-5

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");}}

Page 79: Java Day-5

Synchronization (Contd.)

class ThreadCreator_2 extends Thread{ThreadCreator_1 t;public ThreadCreator_2(ThreadCreator_1 t){this.t = t;}public void run(){t.invoke();

}}

Page 80: Java Day-5

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();

}}

Page 81: Java Day-5

Synchronization (Contd.)

• Output:

Page 82: Java Day-5

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 andsleep for a specified time until another thread calls the notify() method.

• notify(): Wakes up a single thread that is waiting for the monitor of theobject being executed. If multiple threads are waiting, one of them is chosenrandomly.

• notifyAll(): Wakes up all the threads that are waiting for themonitor of the object.

Page 83: Java Day-5

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 andsleep for a specified time until another thread calls the notify() method.

• notify(): Wakes up a single thread that is waiting for the monitor of theobject being executed. If multiple threads are waiting, one of them is chosenrandomly.

• notifyAll(): Wakes up all the threads that are waiting for themonitor of the object.

Page 84: Java Day-5

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");

}}

Page 85: Java Day-5

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");

}

Page 86: Java Day-5

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;

Page 87: Java Day-5

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);

}}

}

Page 88: Java Day-5

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();

} } }

Page 89: Java Day-5

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");

}}

Page 90: Java Day-5

Inter-thread Communication (Contd.)

• Output:

Page 91: Java Day-5

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.

Page 92: Java Day-5

Summary (Contd.)

• To handle exceptions Java provides try-catch-finally exceptional handlercomponents.

• 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.

Page 93: Java Day-5

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.

Page 94: Java Day-5

Summary (Contd.)

• When an instance of the Thread class is created, the thread enters the newthread state.

• When the start() method of a thread is invoked, the thread enters therunnable state.

• A thread enters the dead state when the loop in the run() method iscomplete.

• 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 atime.

• A thread may notify another thread that the task has been completed.• The communication between threads is known as inter-threaded

communication.