SlideShare a Scribd company logo
1 of 35
Object Oriented Programming with Java
Unit No. 4: Exception Handling And Multithreading
Sanjivani Rural Education Societyā€™s
Sanjivani College of Engineering, Kopargaon-423603
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
NAAC ā€˜Aā€™ Grade Accredited, ISO 9001:2015 Certified
Department of Information Technology
(UG Course: NBA Accredited)
Dr. Y.S.Deshmukh
Assistant Professor
Object Oriented Programming with Java
Exception Handling in Java:
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
What is Exception in Java?
Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Object Oriented Programming with Java
Exception Handling in Java:
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Object Oriented Programming with Java
Exception Handling in Java:
Advantage of Exception Handling
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not
be executed. However, when we perform exception handling, the rest of the statements
will be executed. That is why we use exception handling in Java.
Object Oriented Programming with Java
Exception Handling in Java:
Hierarchy of Java Exception classes:
Object Oriented Programming with Java
Types of Java Exceptions:
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
ā€¢ Checked Exception
ā€¢ Unchecked Exception
ā€¢ Error
Object Oriented Programming with Java
Difference between Checked and Unchecked Exceptions:
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Object Oriented Programming with Java
Java Exception Keywords:
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch
or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with
method signature.
Object Oriented Programming with Java
Example of Java Exceptions:
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Object Oriented Programming with Java
Common Scenarios of Java Exceptions:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
Object Oriented Programming with Java
Common Scenarios of Java Exceptions:
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there
may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Object Oriented Programming with Java
Multithreading in Java:
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.
Object Oriented Programming with Java
Multithreading in Java:
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
ā€¢ Process-based Multitasking (Multiprocessing)
ā€¢ Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
ā€¢ Each process has an address in memory. In other words, each process allocates a
separate memory area.
ā€¢ A process is heavyweight.
ā€¢ Cost of communication between the process is high.
ā€¢ Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
Object Oriented Programming with Java
Multithreading in Java:
2) Thread-based Multitasking (Multithreading)
ā€¢ Threads share the same address space.
ā€¢ A thread is lightweight.
ā€¢ Cost of communication between the thread is low.
What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate
path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
Object Oriented Programming with Java
Multithreading in Java:
Object Oriented Programming with Java
Multithreading in Java:
As shown in the Previous figure, a thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside the OS,
and one process can have multiple threads.
Java Thread class
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Object Oriented Programming with Java
Multithreading in Java:
Life cycle of a Thread:
In Java, a thread always exists in any one of the following states. These states are:
ā€¢ New
ā€¢ Active
ā€¢ Blocked / Waiting
ā€¢ Timed Waiting
ā€¢ Terminated
Explanation of Different Thread States
New: Whenever a new thread is created, it is always in the new state. For a thread in
the new state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the
other is running.
Object Oriented Programming with Java
Multithreading in Java:
Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant
of time. It is the duty of the thread scheduler to provide the thread time to run, i.e.,
moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when that
allocated time slice is over, the thread voluntarily gives up the CPU to the other thread,
so that the other threads can also run for their slice of time. Whenever such a scenario
occurs, all those threads that are willing to run, waiting for their turn to run, lie in the
runnable state. In the runnable state, there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.
Object Oriented Programming with Java
Multithreading in Java:
Blocked or Waiting: Whenever a thread is inactive for a span of time (not
permanently) then, either the thread is in the blocked state or is in the waiting state.
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.
Object Oriented Programming with Java
Multithreading in Java:
Object Oriented Programming with Java
Multithreading in Java:
How to create a thread in Java
There are two ways to create a thread:
ā€¢ By extending Thread class
ā€¢ By implementing Runnable interface.
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.
Commonly used Constructors of Thread class:
ā€¢ Thread()
ā€¢ Thread(String name)
ā€¢ Thread(Runnable r)
ā€¢ Thread(Runnable r,String name)
Object Oriented Programming with Java
Multithreading in Java:
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
Object Oriented Programming with Java
Multithreading in Java:
Commonly used methods of Thread class:
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
Object Oriented Programming with Java
Multithreading in Java:
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
public void run(): is used to perform action for a thread.
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:
ā€¢ A new thread starts(with new callstack).
ā€¢ The thread moves from New state to the Runnable state.
ā€¢ When the thread gets a chance to execute, its target run() method will run.
Object Oriented Programming with Java
Multithreading in Java:
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Object Oriented Programming with Java
Multithreading in Java:
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
If you are not extending the Thread class, your class object would not be treated as a
thread object. So you need to explicitly create the Thread class object. We are passing
the object of your class that implements Runnable so that your class run() method may
execute.
Object Oriented Programming with Java
Multithreading in Java:
3) Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors
defined above.
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Object Oriented Programming with Java
Multithreading in Java:
4) Using the Thread Class: Thread(Runnable r, String name)
public class MyThread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}
Object Oriented Programming with Java
Inter-thread Communication in Java:
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the
same critical section to be executed. It is implemented by following methods of Object
class:
ā€¢ wait()
ā€¢ notify()
ā€¢ notifyAll()
Object Oriented Programming with Java
Inter-thread Communication in Java:
1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object, or
a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Object Oriented Programming with Java
Inter-thread Communication in Java:
Understanding the process of inter-thread communication
Object Oriented Programming with Java
Inter-thread Communication in Java:
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise
it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of
the object.
Object Oriented Programming with Java
Inter-thread Communication in Java:
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
Object Oriented Programming with Java
Inter-thread Communication in Java:
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Object Oriented Programming with Java
Thank You

More Related Content

Similar to Unit No 4 Exception Handling and Multithreading.pptx

Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick GuideAnton Shchastnyi
Ā 
Questions of java
Questions of javaQuestions of java
Questions of javaWaseem Wasi
Ā 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
Ā 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdprat0ham
Ā 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |ShubhamAthawane
Ā 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
Ā 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
Ā 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.netJanbask ItTraining
Ā 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfGayathriRHICETCSESTA
Ā 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfGayathriRHICETCSESTA
Ā 
Advantages of java programming language
Advantages of java programming languageAdvantages of java programming language
Advantages of java programming languageamiluafiah
Ā 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1SURBHI SAROHA
Ā 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight ProcessesIsuru Perera
Ā 
Threads in Java
Threads in JavaThreads in Java
Threads in JavaHarshaDokula
Ā 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
Ā 

Similar to Unit No 4 Exception Handling and Multithreading.pptx (20)

Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
Ā 
Questions of java
Questions of javaQuestions of java
Questions of java
Ā 
java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
Ā 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
Ā 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
Ā 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |
Ā 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
Ā 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Ā 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
Ā 
Java interview question
Java interview questionJava interview question
Java interview question
Ā 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
Ā 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
Ā 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
Ā 
Advantages of java programming language
Advantages of java programming languageAdvantages of java programming language
Advantages of java programming language
Ā 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
Ā 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Ā 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Ā 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
Ā 
Java tips
Java tipsJava tips
Java tips
Ā 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
Ā 

More from DrYogeshDeshmukh1

Unit No. 1 Introduction to Java.pptx
Unit No. 1 Introduction to Java.pptxUnit No. 1 Introduction to Java.pptx
Unit No. 1 Introduction to Java.pptxDrYogeshDeshmukh1
Ā 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxDrYogeshDeshmukh1
Ā 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxDrYogeshDeshmukh1
Ā 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxDrYogeshDeshmukh1
Ā 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxDrYogeshDeshmukh1
Ā 
Unit 6 Uncertainty.pptx
Unit 6 Uncertainty.pptxUnit 6 Uncertainty.pptx
Unit 6 Uncertainty.pptxDrYogeshDeshmukh1
Ā 
Unit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptxUnit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptxDrYogeshDeshmukh1
Ā 
Unit 4 Knowledge Representation.pptx
Unit 4 Knowledge Representation.pptxUnit 4 Knowledge Representation.pptx
Unit 4 Knowledge Representation.pptxDrYogeshDeshmukh1
Ā 
Unit 3 Informed Search Strategies.pptx
Unit  3 Informed Search Strategies.pptxUnit  3 Informed Search Strategies.pptx
Unit 3 Informed Search Strategies.pptxDrYogeshDeshmukh1
Ā 
DAA Unit 1 Part 1.pptx
DAA Unit 1 Part 1.pptxDAA Unit 1 Part 1.pptx
DAA Unit 1 Part 1.pptxDrYogeshDeshmukh1
Ā 
Unit 2 Uninformed Search Strategies.pptx
Unit  2 Uninformed Search Strategies.pptxUnit  2 Uninformed Search Strategies.pptx
Unit 2 Uninformed Search Strategies.pptxDrYogeshDeshmukh1
Ā 
Unit 1 Fundamentals of Artificial Intelligence-Part II.pptx
Unit 1  Fundamentals of Artificial Intelligence-Part II.pptxUnit 1  Fundamentals of Artificial Intelligence-Part II.pptx
Unit 1 Fundamentals of Artificial Intelligence-Part II.pptxDrYogeshDeshmukh1
Ā 
Unit 1 Fundamentals of Artificial Intelligence-Part I.pptx
Unit 1  Fundamentals of Artificial Intelligence-Part I.pptxUnit 1  Fundamentals of Artificial Intelligence-Part I.pptx
Unit 1 Fundamentals of Artificial Intelligence-Part I.pptxDrYogeshDeshmukh1
Ā 

More from DrYogeshDeshmukh1 (14)

Unit No. 1 Introduction to Java.pptx
Unit No. 1 Introduction to Java.pptxUnit No. 1 Introduction to Java.pptx
Unit No. 1 Introduction to Java.pptx
Ā 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptx
Ā 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
Ā 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptx
Ā 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
Ā 
Unit 6 Uncertainty.pptx
Unit 6 Uncertainty.pptxUnit 6 Uncertainty.pptx
Unit 6 Uncertainty.pptx
Ā 
Unit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptxUnit 5 Introduction to Planning and ANN.pptx
Unit 5 Introduction to Planning and ANN.pptx
Ā 
Unit 4 Knowledge Representation.pptx
Unit 4 Knowledge Representation.pptxUnit 4 Knowledge Representation.pptx
Unit 4 Knowledge Representation.pptx
Ā 
Unit 3 Informed Search Strategies.pptx
Unit  3 Informed Search Strategies.pptxUnit  3 Informed Search Strategies.pptx
Unit 3 Informed Search Strategies.pptx
Ā 
DAA Unit 1 Part 1.pptx
DAA Unit 1 Part 1.pptxDAA Unit 1 Part 1.pptx
DAA Unit 1 Part 1.pptx
Ā 
AI Overview.pptx
AI Overview.pptxAI Overview.pptx
AI Overview.pptx
Ā 
Unit 2 Uninformed Search Strategies.pptx
Unit  2 Uninformed Search Strategies.pptxUnit  2 Uninformed Search Strategies.pptx
Unit 2 Uninformed Search Strategies.pptx
Ā 
Unit 1 Fundamentals of Artificial Intelligence-Part II.pptx
Unit 1  Fundamentals of Artificial Intelligence-Part II.pptxUnit 1  Fundamentals of Artificial Intelligence-Part II.pptx
Unit 1 Fundamentals of Artificial Intelligence-Part II.pptx
Ā 
Unit 1 Fundamentals of Artificial Intelligence-Part I.pptx
Unit 1  Fundamentals of Artificial Intelligence-Part I.pptxUnit 1  Fundamentals of Artificial Intelligence-Part I.pptx
Unit 1 Fundamentals of Artificial Intelligence-Part I.pptx
Ā 

Recently uploaded

Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
Ā 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
Ā 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
Ā 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
Ā 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
Ā 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
Ā 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
Ā 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
Ā 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
Ā 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniquesugginaramesh
Ā 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
Ā 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
Ā 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
Ā 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
Ā 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
Ā 
Study on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube ExchangerAnamika Sarkar
Ā 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
Ā 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
Ā 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Ā 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Ā 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Ā 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
Ā 
young call girls in Green ParkšŸ” 9953056974 šŸ” escort Service
young call girls in Green ParkšŸ” 9953056974 šŸ” escort Serviceyoung call girls in Green ParkšŸ” 9953056974 šŸ” escort Service
young call girls in Green ParkšŸ” 9953056974 šŸ” escort Service
Ā 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
Ā 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
Ā 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
Ā 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
Ā 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
Ā 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
Ā 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniques
Ā 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
Ā 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
Ā 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
Ā 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
Ā 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Ā 
Study on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned ļ»æTube Exchanger
Ā 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
Ā 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
Ā 

Unit No 4 Exception Handling and Multithreading.pptx

  • 1. Object Oriented Programming with Java Unit No. 4: Exception Handling And Multithreading Sanjivani Rural Education Societyā€™s Sanjivani College of Engineering, Kopargaon-423603 (An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune) NAAC ā€˜Aā€™ Grade Accredited, ISO 9001:2015 Certified Department of Information Technology (UG Course: NBA Accredited) Dr. Y.S.Deshmukh Assistant Professor
  • 2. Object Oriented Programming with Java Exception Handling in Java: The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. What is Exception in Java? Exception is an abnormal condition. In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. What is Exception Handling? Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
  • 3. Object Oriented Programming with Java Exception Handling in Java: Advantage of Exception Handling The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario: statement 1; statement 2; statement 3; statement 4; statement 5;//exception occurs statement 6; statement 7; statement 8; statement 9; statement 10;
  • 4. Object Oriented Programming with Java Exception Handling in Java: Advantage of Exception Handling Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.
  • 5. Object Oriented Programming with Java Exception Handling in Java: Hierarchy of Java Exception classes:
  • 6. Object Oriented Programming with Java Types of Java Exceptions: There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely: ā€¢ Checked Exception ā€¢ Unchecked Exception ā€¢ Error
  • 7. Object Oriented Programming with Java Difference between Checked and Unchecked Exceptions: 1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3) Error Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 8. Object Oriented Programming with Java Java Exception Keywords: Java provides five keywords that are used to handle the exception. The following table describes each. Keyword Description try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
  • 9. Object Oriented Programming with Java Example of Java Exceptions: public class JavaExceptionExample{ public static void main(String args[]){ try{ //code that may raise exception int data=100/0; }catch(ArithmeticException e){System.out.println(e);} //rest code of the program System.out.println("rest of the code..."); } }
  • 10. Object Oriented Programming with Java Common Scenarios of Java Exceptions: 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. int a=50/0;//ArithmeticException 2) A scenario where NullPointerException occurs If we have a null value in any variable, performing any operation on the variable throws a NullPointerException. String s=null; System.out.println(s.length());//NullPointerException 3) A scenario where NumberFormatException occurs If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException. String s="abc"; int i=Integer.parseInt(s);//NumberFormatException
  • 11. Object Oriented Programming with Java Common Scenarios of Java Exceptions: 4) A scenario where ArrayIndexOutOfBoundsException occurs When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements. int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  • 12. Object Oriented Programming with Java Multithreading in Java: Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation, etc. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time. 2) You can perform many operations together, so it saves time. 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
  • 13. Object Oriented Programming with Java Multithreading in Java: Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways: ā€¢ Process-based Multitasking (Multiprocessing) ā€¢ Thread-based Multitasking (Multithreading) 1) Process-based Multitasking (Multiprocessing) ā€¢ Each process has an address in memory. In other words, each process allocates a separate memory area. ā€¢ A process is heavyweight. ā€¢ Cost of communication between the process is high. ā€¢ Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.
  • 14. Object Oriented Programming with Java Multithreading in Java: 2) Thread-based Multitasking (Multithreading) ā€¢ Threads share the same address space. ā€¢ A thread is lightweight. ā€¢ Cost of communication between the thread is low. What is Thread in java A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.
  • 15. Object Oriented Programming with Java Multithreading in Java:
  • 16. Object Oriented Programming with Java Multithreading in Java: As shown in the Previous figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads. Java Thread class Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
  • 17. Object Oriented Programming with Java Multithreading in Java: Life cycle of a Thread: In Java, a thread always exists in any one of the following states. These states are: ā€¢ New ā€¢ Active ā€¢ Blocked / Waiting ā€¢ Timed Waiting ā€¢ Terminated Explanation of Different Thread States New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution. Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states within it: one is runnable, and the other is running.
  • 18. Object Oriented Programming with Java Multithreading in Java: Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state. A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie. Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.
  • 19. Object Oriented Programming with Java Multithreading in Java: Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state. Terminated: A thread reaches the termination state because of the following reasons: When a thread has finished its job, then it exists or terminates normally. Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault. A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can respawn (active after kill) the dead thread.
  • 20. Object Oriented Programming with Java Multithreading in Java:
  • 21. Object Oriented Programming with Java Multithreading in Java: How to create a thread in Java There are two ways to create a thread: ā€¢ By extending Thread class ā€¢ By implementing Runnable interface. 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. Commonly used Constructors of Thread class: ā€¢ Thread() ā€¢ Thread(String name) ā€¢ Thread(Runnable r) ā€¢ Thread(Runnable r,String name)
  • 22. Object Oriented Programming with Java Multithreading in Java: Commonly used methods of Thread class: public void run(): is used to perform action for a thread. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. public void join(): waits for a thread to die. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. public int getPriority(): returns the priority of the thread. public int setPriority(int priority): changes the priority of the thread. public String getName(): returns the name of the thread. public void setName(String name): changes the name of the thread. public Thread currentThread(): returns the reference of currently executing thread.
  • 23. Object Oriented Programming with Java Multithreading in Java: Commonly used methods of Thread class: public int getId(): returns the id of the thread. public Thread.State getState(): returns the state of the thread. public boolean isAlive(): tests if the thread is alive. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend(): is used to suspend the thread(depricated). public void resume(): is used to resume the suspended thread(depricated). public void stop(): is used to stop the thread(depricated). public boolean isDaemon(): tests if the thread is a daemon thread. public void setDaemon(boolean b): marks the thread as daemon or user thread. public void interrupt(): interrupts the thread. public boolean isInterrupted(): tests if the thread has been interrupted. public static boolean interrupted(): tests if the current thread has been interrupted.
  • 24. Object Oriented Programming with Java Multithreading in Java: Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. Starting a thread: The start() method of Thread class is used to start a newly created thread. It performs the following tasks: ā€¢ A new thread starts(with new callstack). ā€¢ The thread moves from New state to the Runnable state. ā€¢ When the thread gets a chance to execute, its target run() method will run.
  • 25. Object Oriented Programming with Java Multithreading in Java: 1) Java Thread Example by extending Thread class class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } }
  • 26. Object Oriented Programming with Java Multithreading in Java: 2) Java Thread Example by implementing Runnable interface class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r) t1.start(); } } If you are not extending the Thread class, your class object would not be treated as a thread object. So you need to explicitly create the Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.
  • 27. Object Oriented Programming with Java Multithreading in Java: 3) Using the Thread Class: Thread(String Name) We can directly use the Thread class to spawn new threads using the constructors defined above. public class MyThread1 { // Main method public static void main(String argvs[]) { // creating an object of the Thread class using the constructor Thread(String name) Thread t= new Thread("My first thread"); // the start() method moves the thread to the active state t.start(); // getting the thread name by invoking the getName() method String str = t.getName(); System.out.println(str); } }
  • 28. Object Oriented Programming with Java Multithreading in Java: 4) Using the Thread Class: Thread(Runnable r, String name) public class MyThread2 implements Runnable { public void run() { System.out.println("Now the thread is running ..."); } // main method public static void main(String argvs[]) { // creating an object of the class MyThread2 Runnable r1 = new MyThread2(); // creating an object of the class Thread using Thread(Runnable r, String name) Thread th1 = new Thread(r1, "My new thread"); // the start() method moves the thread to the active state th1.start(); // getting the thread name by invoking the getName() method String str = th1.getName(); System.out.println(str); } }
  • 29. Object Oriented Programming with Java Inter-thread Communication in Java: Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class: ā€¢ wait() ā€¢ notify() ā€¢ notifyAll()
  • 30. Object Oriented Programming with Java Inter-thread Communication in Java: 1) wait() method The wait() method causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. 2) notify() method The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. 3) notifyAll() method Wakes up all threads that are waiting on this object's monitor.
  • 31. Object Oriented Programming with Java Inter-thread Communication in Java: Understanding the process of inter-thread communication
  • 32. Object Oriented Programming with Java Inter-thread Communication in Java: The point to point explanation of the above diagram is as follows: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. 4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). 5. Now thread is available to acquire lock. 6. After completion of the task, thread releases the lock and exits the monitor state of the object.
  • 33. Object Oriented Programming with Java Inter-thread Communication in Java: class Customer{ int amount=10000; synchronized void withdraw(int amount){ System.out.println("going to withdraw..."); if(this.amount<amount){ System.out.println("Less balance; waiting for deposit..."); try{wait();}catch(Exception e){} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount){ System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } }
  • 34. Object Oriented Programming with Java Inter-thread Communication in Java: class Test{ public static void main(String args[]){ final Customer c=new Customer(); new Thread(){ public void run(){c.withdraw(15000);} }.start(); new Thread(){ public void run(){c.deposit(10000);} }.start(); }}
  • 35. Object Oriented Programming with Java Thank You