0% found this document useful (0 votes)
2 views77 pages

Java Unit3

This document covers exception handling and multithreading in Java, detailing the definitions, types of exceptions, and the use of keywords such as try, catch, throw, throws, and finally. It distinguishes between errors and exceptions, explains the exception hierarchy, and provides examples of built-in exceptions, checked and unchecked exceptions, and the syntax for handling exceptions. Additionally, it discusses the advantages of exception handling and the differences between the throw and throws keywords.

Uploaded by

nissatahseen17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views77 pages

Java Unit3

This document covers exception handling and multithreading in Java, detailing the definitions, types of exceptions, and the use of keywords such as try, catch, throw, throws, and finally. It distinguishes between errors and exceptions, explains the exception hierarchy, and provides examples of built-in exceptions, checked and unchecked exceptions, and the syntax for handling exceptions. Additionally, it discusses the advantages of exception handling and the differences between the throw and throws keywords.

Uploaded by

nissatahseen17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT III

Exception Handling and Multithreading: Exception-Handling


Fundamentals, Exception Types, Using try catch, throw throws and
finally keywords, Built-in Exceptions, Creating own exception
subclasses. Multithreading: Life cycle of a thread, creating
threads,thread priorities, Synchronizing threads, Inter thread
Communication.
EXCEPTION
Definition: An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.

Difference between Error and Exception


Here are the differences between Errors and Exceptions in Java:
Exceptions
• Exceptions represent conditions (RECOVERABLE PROBLEMS)that can occur during the normal execution of a
program and can be handled by application code.
• Application code handles exceptions, which represent conditions that can occur during the normal execution of a
program.
• Examples of exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and
ArithmeticException.
• Exceptions are subclasses of the Exception class, which extends Throwable.
Errors
• Errors represent serious, unrecoverable problems that typically result from system-level issues or resource
exhaustion.
• The application code generally does not handle errors, as they are beyond its control
• Examples of errors include OutOfMemoryError, StackOverflowError, and VirtualMachineError.
• Errors are unchecked and are subclasses of the Error class, which extends Throwable.
Error Exception

An Error indicates a serious problem that a


Exception indicates conditions that a reasonable application might try to catch
reasonable application should not try to catch.

This is caused by issues with the JVM or hardware. This is caused by conditions in the program such as invalid input or logic errors.

Examples: OutOfMemoryError, StackOverFlowError Examples: IOException, NullPointerException


Exception Handling:
• Exception Handling in Java is an effective method for dealing with unwanted and unexpected events during
program execution that disrupt the normal flow of a program's execution.
• Even if your code compiles successfully and looks error-free, some problems may only appear when the program
runs. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code.
• When an exception occurs, the program stops executing and displays an error message unless the exception is
properly handled, these are known as runtime errors, and Java handles them using exceptions.
• Java Exception handling is a technique for handling different types of errors while maintaining the application's
usual flow.
• A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece
of code.
• When an exceptional condition arises, an object representing that exception is created and thrown in the method
that caused the error, that method may choose to handle the exception itself, or pass it on.
DEFINITIION
Exception Handling is a way of handling errors that occur during runtime and compile time.
It maintains your program flow despite runtime errors in the code and, thus, prevents unanticipated crashes.

Major reasons why an exception Occurs


User’s Invalid Input- If a user enters input that the program is not expecting (e.g., entering a string when a number is
expected), it can lead to exceptions like Number Format Exception.
Database Connection Error- When the program cannot connect to the database (due to incorrect URL, credentials, or
server issues), it may throw a SQLException.
System Failure- Hardware issues such as disk failure or insufficient memory can cause unexpected exceptions during
program execution.
Network Problems- If your Java application depends on internet or server connections and the network is unavailable,
exceptions like IO Exception or Socket Exception may occur.
Security Compromises- When code tries to access a restricted resource without permission, a Security Exception can be
thrown.
Errors in Code (Logical or Runtime)- Mistakes in code, such as dividing by zero or accessing null references, are
common causes of exceptions like Arithmetic Exception or Null Pointer Exception.
Advantages of Exceptions Handling
Separating Error-Handling Code from "Regular" Code
1)Propagating Errors Up the Call Stack
2)Grouping and Differentiating Error Types
3)Provision to Complete Program Execution
Exception Hierarchy :
• All exception classes are subtypes of the [Link] class.
• The exception class is a subclass of the Throwable class. Other than the exception class there is
another subclass called Error which is derived from the Throwable class.
• Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed
by Exception the other branch is topped by Error.
In Java, all exceptions and errors are subclasses of the Throwable class. It has two main branches
[Link]. [Link]

1. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to handle common errors during program
execution. There are tw type of built-in exception in java.

Checked Exceptions

Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time
by the compiler. Examples of Checked Exception are listed below:
•ClassNotFoundException: Throws when the program tries to load a class at runtime but the class is not found
because it's belong not present in the correct location or it is missing from the project.

•InterruptedException: Thrown when a thread is paused and another thread interrupts it.

•IOException: Throws when input/output operation fails.

•InstantiationException: Thrown when the program tries to create an object of a class but fails because the
class is abstract, an interface or has no default constructor.

•SQLException: Throws when there is an error with the database.

•FileNotFoundException: Thrown when the program tries to open a file that does not exist.
Unchecked Exceptions

The unchecked exceptions are just opposite to the checked exceptions. The compiler
will not check these exceptions at compile time. In simple words, if a program throws an
unchecked exception and even if we did not handle or declare it, the program would
not give a compilation error. Examples of Unchecked Exception are listed below:
•ArithmeticException: It is thrown when there is an illegal math operation.

•ClassCastException: It is thrown when we try to cast an object to a class it does not


belong to.

•NullPointerException: It is thrown when we try to use a null object (e.g. accessing its
methods or fields).

•ArrayIndexOutOfBoundsException: This occurs when we try to access an array


element with an invalid index.

•ArrayStoreException: This happens when we store an object of the wrong type in an


array.

•IllegalThreadStateException: It is thrown when a thread operation is not allowed in


its current state.
Checked Exceptions: Unchecked Exceptions:

import [Link]; Example


import [Link]; public class Unchecked_Demo
public class FilenotFound_Demo { public static void main(String args[])
{ { int num[] = {1, 2, 3, 4};
public static void main(String args[]) [Link](num[5]);
{ }}
File file = new File("E://[Link]"); If you compile and execute the above program,
FileReader fr = new FileReader(file); you will get the following exception.
}} Output
If you try to compile the above program, you will get the Exception in thread "main"
following exceptions. [Link]:
Output 5
C:\>javac FilenotFound_Demo.java at
FilenotFound_Demo.java: 8: error: unreported exception Exceptions.Unchecked_Demo.main(Unchecke
FileNotFoundException; must be caught or declared to d_Demo.java:8)
be thrown
FileReader fr = new FileReader(file); ^1 error
Try Block
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

TRY : Program statements that you want to monitor for exceptions are contained within a try block.

Try { // block of code to monitor for errors

Throw exceptobj1;

}catch (ExceptionType1 exOb)

{ // exception handler for ExceptionType1 }

catch (ExceptionType2 exOb)

{ // exception handler for ExceptionType2 }

// ... finally { // block of code to be executed after try block ends }

Here, ExceptionType is the type of exception that has occurred.


Using try and catch: Displaying a Description of an Exception You
It is useful to handle an exception yourself. Doing can display this description in a println( ) statement
so provides two benefits. by simply passing the exception as an argument. For
-First, it allows you to fix the error. example, the catch block in the preceding program
-Second, it prevents the program from can be rewritten like this:
automatically terminating.
catch (ArithmeticException e)
import [Link].*;
{
class Sample {
public static void main(String[] args) { [Link]("Exception: " + e);
try {
// This will throw an ArithmeticException a = 0;
int res = 10 / 0; // set a to zero and continue
}
// Here we are Handling the exception }
catch (ArithmeticException e) {
When this version is substituted in the program, and
[Link]("Exception caught: " + e);
} the program is run, each divide-by- zero error
[Link]("I will always execute"); displays the following message:
}}
Exception: [Link]: / by zero.
Output
Exception caught: [Link]: / by zero
I will always execute
Multiple catch Blocks Example Multiple Catch
In some cases, more than one exception public class ExcepTest {
could be raised by a single piece of code.
To handle this type of situation, you can
public static void main(String args[]) {
specify two or more catch clauses, each
try {
int a[] = new int[2];
catching a different type of exception.
int b = 0;
Multiple catch blocks in Java are used to
int c = 1/b;
catch/handle multiple exceptions that
[Link]("Access element three :" + a[3]);
may be thrown from a particular code
}
section.
catch (ArrayIndexOutOfBoundsException e) {
A try block can have multiple catch
[Link]("ArrayIndexOutOfBoundsException thrown :" + e);
blocks to handle multiple exceptions.
}
Syntax: try { catch (Exception e) {
// Protected code [Link]("Exception thrown :" + e);
} catch (ExceptionType1 e1) { }
// Catch block [Link]("Out of the block");
} catch (ExceptionType2 e2) { }
// Catch block }
} catch (ExceptionType3 e3) { Output
// Catch block Exception thrown :[Link]: / by zero
} Out of the block
Example Nested Try:
Nested try Statements public class ExcepTest {
The try statement can be nested. That is, a try statement can public static void main(String args[]) {
be inside the block of another try. try {
int a[] = new int[2];
try {
Syntax: int b = 0;
try { // parent try block int c = 1/b;
}
try
catch(Exception e) {
{ // child try block [Link]("Exception thrown: " + e);
} }
[Link]("Access element three :" + a[3]);
catch(ExceptionType1 e1) }
{ // child catch block catch (ArrayIndexOutOfBoundsException e) {
} [Link]("Exception thrown: " + e);
}
} catch (ExceptionType2 e1) [Link]("Out of the block");
{ // parent catch block }}
} Output
Exception thrown: [Link]: / by zero
Exception thrown: [Link]:
3
Out of the block
Throw
The throw keyword in Java is used to explicitly throw an
exception from a method or any block of code.
We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom
exceptions. (user defined)
Syntax:
throw Instance
Where instance is an object of type Throwable.
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e., Instance must be of
type Throwable or a subclass of Throwable.
If no matching catch is found then the default exception
handler will halt the program.
Example Throw
Ex. 1 class Sample { Ex. 2 class Sample1 {
static void fun() public static void main(String[] args){
{ int numerator = 1;
try { int denominator = 0;
throw new NullPointerException("demo");
} if (denominator == 0) {
catch (NullPointerException e) { // Manually throw an ArithmeticException
[Link]("Caught inside fun()."); throw new ArithmeticException("Cannot divide by
throw e; // rethrowing the exception zero");
} } else {
} [Link](numerator / denominator);
public static void main(String args[]) }
{ }
try { }
fun(); Output :
} Exception in thread "main" [Link]:
catch (NullPointerException e) { Cannot divide by zero at 9
[Link]("Caught in main.");
}
}
}
Output : Caught inside fun().
Caught in main.
Throws:
• Throws: A throws clause lists the types of exceptions that a method might throw.

• All other exceptions that a method can throw must be declared in the throws clause. If they are not, a
compile-time error will result.

• This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list

{ // body of method }

• Here, exception-list is a comma-separated list of the exceptions that a method can throw.

So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is
possible for your program to throw an exception explicitly, using the throw statement.
The general form of throw is shown here: Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable
Syntax: Throw ThrowableInstance;
Throw e;
• throws is a keyword in Java that is used in the signature of a method to indicate
that this method might throw one of the listed type exceptions.
• The caller to these methods has to handle the exception using a try-catch
block.
• In a program, if there is a chance of raising an exception then the compiler
always warns us about it and we must handle that checked exception,
Otherwise, we will get compile time error saying unreported exception XXX
must be caught or declared to be thrown. To prevent this compile time error
we can handle the exception in two ways:
• By using try catch
• By using the throws keyword
Ex. class Sample { Ex. import [Link].*;
static void fun() throws IllegalAccessException class Main {
{ public static void findFile() throws IOException {
[Link]("Inside fun(). "); File newFile=new File("[Link]");
throw new IllegalAccessException("demo"); FileInputStream stream=new FileInputStream(newFile);
} }
public static void main(String args[])
{ public static void main(String[] args) {
try { try{
fun(); findFile();
} } catch(IOException e){
catch (IllegalAccessException e) { [Link](e);
[Link]("Caught in main."); }
} } } }
Output } OUTPUT : [Link]: [Link] (No such file
Inside fun(). or directory)
Caught in main. If a method does not handle exceptions, the type of exceptions
We can use the throws keyword to delegate the that may occur within it must be specified in the throws clause
responsibility of exception handling to the caller (It may be so that methods further up in the call stack can handle them or
a method or JVM) then the caller method is responsible to specify them using throws keyword themselves.
handle that [Link] below example throwing a The findFile() method specifies that an IOException can be
IllegalAccessException from a method and handling it in the thrown. The main() method calls this method and handles the
main method using a try-catch block. exception if it is thrown.
DIFFERENCE BETWEEN THROW AND THROWS
[Link]. THROW THROWS
1 Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an
exception. exception.
2 Throw is followed by an instance Throws is followed by class

3 Throw is used within the method. Throws is used with the method signature.
4 We cannot throw multiple exceptions. You can declare multiple exceptions.
5 It can throw both checked and unchecked It is only used for checked exceptions.
exceptions. Unchecked exceptions do not require throws
6. The method's caller is responsible for
The method or block throws the exception.
handling the exception.
7. public void myMethod() throws IOException
throw new ArithmeticException("Error");
{}
8. It forces the caller to handle the declared
Stops the current flow of execution immediately.
exceptions.
Finally:
The finally block in java is used to put important codes Ex. class Sample2 {
such as clean up code e.g. closing the file or closing public static void main(String[] args)
the connection. {
The finally block executes whether exception rise or try {
not and whether exception handled or not. [Link]("inside try block");
A finally contains all the crucial statements regardless of // Not throw any exception
the exception occurs or not. [Link](34 / 2);
Syntax : }
try { catch (ArithmeticException e) {
// Protected code [Link]("Arithmetic Exception");
} catch (ExceptionType1 e1) { }
// Catch block finally
} catch (ExceptionType2 e2) { [Link]("finally : i execute
// Catch block always.");
} catch (ExceptionType3 e3) { }} }
// Catch block Output
}finally { inside try block
// The finally block always 17
executes. finally : i execute always.
}
Points To Remember While Using Finally Block
•A catch clause cannot exist without a try statement.
•It is not compulsory to have finally clauses whenever a try/catch block is present.
•The try block cannot be present without either catch clause or finally clause.
•Any code cannot be present in between the try, catch, finally blocks.
•finally block is not executed in case exit() method is called before finally block or a fatal
error occurs in program execution.
•finally block is executed even method returns a value before finally block.
Why Java Finally Block Used?
Java finally block can be used for clean-up (closing) the connections, files opened, streams, etc.
those must be closed before exiting the program.
It can also be used to print some final information.
built in exception
• ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.

• ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative
or greater than or equal to the size of the array.

• ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found

• FileNotFoundException
This Exception is raised when a file is not accessible or does not open.

• IOException
It is thrown when an input-output operation failed or interrupted

• InterruptedException
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.

• NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
• NoSuchMethodException
It is thrown when accessing a method which is not found.

• NullPointerException
This exception is raised when referring to the members of a
null object. Null represents nothing

• NumberFormatException
This exception is raised when a method could not convert a
string into a numeric format.

• RuntimeException
This represents any exception which occurs during runtime.

• StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index
is either negative or greater than the size of the string.
Java’s Built-in Exceptions 2. ArrayIndexOutOfBounds Exception
1. Arithmetic exception // Java program to demonstrate
// ArrayIndexOutOfBoundException
// Java program to demonstrate class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
// ArithmeticException
{
class ArithmeticException_Demo { try {
int a[] = new int[5];
public static void main(String args[]) a[6] = 9; // accessing 7th element in an array of
// size 5
{ try {
}
int a = 30, b = 0; catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index is Out Of Bounds");
int c = a / b; // cannot divide by zero }
}
[Link]("Result = " + c);
}
} catch (ArithmeticException e) {
Output:
[Link]("Can't divide a number by 0"); } }}
Array Index is Out Of Bounds
Output:Can't divide a number by 0
[Link] :
// Java program to illustrate the 4. FileNotFoundException :

// concept of ClassNotFoundException // Java program to demonstrate FileNotFoundException


import [Link];
class Bishal { } import [Link];
import [Link];
class Great { }
class File_notFound_Demo {
class MyClass { public static void main(String args[])
{
public static void main(String[] args) try {
// Following file does not exist
{
File file = new File("E:// [Link]");
Object o = [Link](args[0]).newInstance();
FileReader fr = new FileReader(file);
//ForName(String) Returns the Class object associated with the class }
//or interface with the given string name. catch (FileNotFoundException e) {
[Link]("File does not exist");
[Link]("Class created for" + [Link]().getName());
}
} }
}
} Output: File does not exist
Output: ClassNotFoundException
5. IOException :
6. InterruptedException :
// Java program to illustrate IOException // Java Program to illustrate
import [Link].*; // InterruptedException (Thrown when a thread is
class Sample { waiting, sleeping, or otherwise occupied, and the
public static void main(String args[]) thread is interrupted, either before or during the
{ activity. )
FileInputStream f = null;
class Sample {
f = new FileInputStream("[Link]");
int i;
public static void main(String args[])

while ((i = [Link]()) != -1) { {


[Link]((char)i);
Thread t = new Thread();
} [Link]();
[Link](10000);
}}
}}
Output:error: unreported exception IOException; must be caught or
declared to be thrown
Output:error: unreported exception InterruptedException;
must be caught or declared to be thrown
7. NoSuchMethodException :
8. NullPointerException :
// Java Program to illustrate NoSuchMethodException

import [Link].*; // Java program to demonstrate NullPointerException


class NoSuchMethodError { class NullPointer_Demo {
public void display(String s){ // Java program to demonstrate NullPointerException
[Link]("String obtained is " +s); class NullPointer_Demo {
} public static void main(String args[])
} {
try {
public class Main {
String a = null; // null value
public static void main(String[] args){ [Link]([Link](0));
NoSuchMethodError A = new NoSuchMethodError }
();
catch (NullPointerException e) {
[Link]("Java"); [Link]("NullPointerException..");
} }
}
public class Main { }
^ }
/tmp/ghTvaEUC9E/[Link]: error: Output:NullPointerException..
cannot find symbol
[Link]("Java");
^ symbol: method print(String)
location: variable A of type NoSuchMethodError
2 errors
9. NumberFormatException 10. StringIndexOutOfBoundsException

// Java program to demonstrate


// Java program to demonstrate
// NumberFormatException // StringIndexOutOfBoundsException
class NumberFormat_Demo {
class StringIndexOutOfBound_Demo {
public static void main(String args[]) public static void main(String args[])
{ {
try {
try { String a = "This is like chipping "; // length is 22
// “sample" is not a number char c = [Link](24); // accessing 25th element
[Link](c);
int num = [Link](“sample"); }
[Link](num); catch (StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
}
catch (NumberFormatException e) { }
[Link]("Number format exception"); }
Output:
} }}
StringIndexOutOfBoundsException
Output: Number format exception
creating User defined exceptions:
Java provides us the facility to create our own exceptions by extending the Java Exception class. Creating our own
Exception is known as a custom exception in Java or a user-defined exception in Java and throwing that
exception using the "throw" keyword.
There are two types of custom exceptions in Java.
Checked Exceptions: It extends the Exception class. and it must be declared in the throws clause of the method signature.
Unchecked Exceptions: It extends the RuntimeException class.
We use Java custom exception,
To represent application-specific errors.
To add clear, descriptive error messages for better debugging.
To encapsulate business logic errors in a meaningful way.
Create a User-Defined Custom Exception
Create a new class that extends Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).
Provide constructors to initialize the exception with custom messages.
Add methods to provide additional details about the exception. (this is optional)
Ex.1. // A Class that represents user-defined exception EX. 2
class MyException extends Exception {
public MyException(String m) {
super(m);
}
}
// A Class that uses the above MyException
public class setText {
public static void main(String args[]) {
try {

// Throw an object of user-defined exception


throw new MyException("This is a custom exception");
}
catch (MyException ex) {
[Link]("Caught");
[Link]([Link]()); OUTPUT :
Caught exception
} Invalid Entry
}
}
Output
Caught
This is a custom exception
EX. public class Main { EX. public class Main {
public static void main(String[] args) { static void checkAge(int age) {
try { if (age < 18) {
int[] myNumbers = {1, 2, 3}; throw new ArithmeticException("Access denied - You must be at least
[Link](myNumbers[10]); 18 years old.");
} catch (Exception e) { }
[Link]("Something went wrong."); else {
} [Link]("Access granted - You are old enough!");
} }
} }
OUTPUT: Something went wrong. public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
OUTPUT : Exception in thread "main" [Link]:
Access denied - You must be at least 18 years old.
at [Link]([Link])
at [Link]([Link])

Ex. Write a Java program to create a method that takes an


integer as a parameter and throws an exception if the number
is odd.
Ex. // A Class that represents use-defined exception Steps for creation of User Defined
class MyException extends Exception { Exception class :
}// A Class that uses above MyException Although Java’s built-in exceptions handle most common
errors, you will probably want to create your own exception
public class setText { types to handle situations specific to your applications. This is
quite easy to do:
public static void main(String args[])
1) just define a subclass of Exception (which is, of course, a
{ try { // Throw an object of user defined exception subclass of Throwable).

throw new MyException();


2) Your subclasses don’t need to actually implement
anything—it is their existence in the type system that allows
} catch (MyException ex) { you to use them as exceptions.
3) The Exception class does not define any methods of its
[Link]("Caught");
own. It does, of course, inherit those methods provided by
[Link]([Link]());
Throwable.
4) Thus, all exceptions, including those that you create, have
} }} the methods defined by Throwable available to them.
Output :Caught

null
1) What is wrong with the following code? Why it 2) What will be the output of the following program?
is showing compilation error?
public class JavaExceptionHandlingQuiz
public class JavaExceptionHandlingQuiz {
1 public static void main(String[] args)
{
2 {
public static void main(String[] args)
3 int i = 1;
{
4
try try
5
{ {
6
[Link]("Try Block"); i++;
7
} }
8
9 catch (Exception e)
[Link]("-----"); {
10
11 i++;
catch (Exception e) }
12
{
13 finally
[Link]("Catch Block");
14 {
}
15
}
i++;
16 }
}
17 [Link](i); }}
View Answer View Answer
There should not be any other statements in between try and 3
catch blocks.
3) What will be the output of the following program? 4) What will be the output of the following program?
public class JavaExceptionHandlingQuiz
{ public class JavaExceptionHandlingQuiz
public static void main(String[] args) {
{ public static void main(String[] args)
try {
{ [Link](1); try
{
int i = 100 / 0; [Link](1);
}
[Link](2); catch (Exception e)
} {
catch (Exception e) [Link](2);
{ }
[Link](3);
} [Link](3);
}}
finally {
View Answer
[Link](4);
1
} }}
3 View Answer
Compile time error. try, catch and finally blocks together form one
unit. There should not be any other statements in between try-catch-
finally blocks.
What is Process?
• A process is an instance of a program that is being
executed.
• When we run a program, it does not execute directly.
• It takes some time to follow all the steps required to
execute the program, and following these execution steps is
known as a process.
• A process can create other processes to perform multiple
tasks at a time; the created processes are known as clone or
child process, and the main process is known as the parent
process.
• Each process contains its own memory space and does not
share it with the other processes.
• It is known as the active entity. A typical process remains
in the below form in memory.
A process in OS can remain in any of the following states:
•NEW: A new process is being created.
•READY: A process is ready and waiting to be allocated to a
processor.
What is Thread?
• A thread is the subset of a process and is also known as the lightweight
process.
• A process can have more than one thread, and these threads are managed
independently by the scheduler.
• All the threads within one process are interrelated to each other.
• Threads have some common information, such as data segment, code segment,
files, etc., that is shared to their peer threads. But contains its own
registers, stack, and counter.
How does thread work?
• Thread is a subprocess or an execution unit within a process. A process can

contain a single thread to multiple threads. A thread works as follows:

• When a process starts, OS assigns the memory and resources to it.

• Each thread within a process shares the memory and resources of that process

only.

• Threads are mainly used to improve the processing of an application.

• In reality, only a single thread is executed at a time, but due to fast context

switching between threads gives an illusion that threads are running parallelly.

• If a single thread executes in a process, it is known as a single-threaded And

if multiple threads execute simultaneously, then it is known as multithreading.


Process Thread
Process means any program is in execution. Thread means a segment of a process.
The process takes more time to terminate. The thread takes less time to terminate.
It takes more time for creation. It takes less time for creation.
It also takes more time for context switching. It takes less time for context switching.
The process is less efficient in terms of
Thread is more efficient in terms of communication.
communication.
We don’t need multi programs in action for multiple
Multiprogramming holds the concepts of multi-
threads because a single process consists of multiple
process.
threads.
The process is isolated. Threads share memory.
A Thread is lightweight as each thread in a process
The process is called the heavyweight process.
shares code, data, and resources.
Thread switching does not require calling an
Process switching uses an interface in an operating
operating system and causes an interrupt to the
system.
kernel.
If one process is blocked, then it will not affect the If a user-level thread is blocked, then all other user-
execution of other processes. level threads are blocked.
The process has its own Process Control Block, Stack, Thread has Parents’ PCB, its own Thread Control
and Address Space. Block, and Stack and common Address space.
Since all threads of the same process share address
Changes to the parent process do not affect child space and other resources so any changes to the
processes. main thread may affect the behaviour of the other
threads of the process.
A system call is involved in it. No system call is involved.
The process does not share data with each other. Threads share data with each other.
Multithreading
Multitasking is being achieved in two ways :
Multiprocessing : Process-based multitasking is a heavyweight process and occupies different address
spaces in memory. Hence, while switching from one process to another, it will require some time be it very
small, causing a lag because of switching.
Multithreading : Thread-based multitasking is a lightweight process and occupies the same address space.
Hence, while switching cost of communication will be very less.

• Multithreading is a Java feature that enables the concurrent execution of two or more parts
of a program, maximizing CPU utilization.
• By definition, multitasking is when multiple processes share common processing resources such as a
CPU.
• The OS divides processing time not only among different applications, but also among each thread
within an application.
• Each part of such a program is called a thread. So, threads are lightweight processes within a
process.
• Threads allows a program to operate more efficiently by doing multiple things at the same time.
• Threads can be used to perform complicated tasks in the background without interrupting the main
program.
Multithreading -Definition Advantages of Java Multithreading
1) It doesn't block the user because threads
are independent and you can perform
It is a process of executing multiple threads simultaneously.
multiple operations at the same time.
A thread is a lightweight sub-process, the smallest unit of processing
2) You can perform many operations
Threads allows a program to operate more efficiently by doing
together, so it saves time.
multiple things at the same time.
3) Threads are independent, so it doesn't
Threads can be used to perform complicated tasks in the background affect other threads if an exception occurs in
without interrupting the main program. a single thread.
.
Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
i)Runnable
ii)Running
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
Life cycle of a thread :
A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.
Following are the stages of the life cycle −
•New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
•Runnable − After a newly born thread is started, the thread becomes runnable.
A thread in this state is considered to be executing its task.
•Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
•Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
•Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.
Creating Threads:
Threads can be created by using two mechanisms : Extending the Thread class and Implementing the Runnable
Interface

1) Thread creation by extending the Thread class


We create a class that extends the [Link] class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method.
Creating threads
There are two different ways to create a thread in Java. We have listed them as follows:
• By Extending a Thread Class
• By Implementing a Runnable Interface

1) By Extending a Thread Class


It can be created by extending the Thread class and overriding its run() method:
public class Main extends Thread {
public void run() {
[Link]("This code is running in a thread");
}
}

2) By Implementing a Runnable Interface


Another way to create a thread is to implement the Runnable interface:
public class Main implements Runnable {
public void run() {
[Link]("This code is running in a thread");
}
}
Create a Thread by Extending a Thread Class
This way to create a thread is to create a new class that extends Thread class using the following two
simple steps. This approach provides more flexibility in handling multiple threads created using
available methods in Thread class.

Step 1
You will need to override run() method available in Thread class. This method provides an entry point
for the thread and you will put your complete business logic inside this method. Following is a simple
syntax of run() method −
public void run( )

Step 2
Once Thread object is created, you can start it by calling start() method, which executes a call to run( )
method. Following is a simple syntax of start() method −
void start( );
Create a Thread by Implementing a Runnable Interface
If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable
interface. You will need to follow three basic steps −

Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an
entry point for the thread and you will put your complete business logic inside this method. Following is a simple
syntax of the run() method −

public void run( )


Step 2
As a second step, you will instantiate a Thread object using the following constructor −

Thread(Runnable threadObj, String threadName);


Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name
given to the new thread.

Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method.
Following is a simple syntax of start() method −(belongs to Thread class)
void start();
Java code for thread creation by extending the Thread public class Multithread {
public static void main(String[] args)
class
{
class MultithreadingDemo extends Thread { int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
public void run() MultithreadingDemo object
= new MultithreadingDemo();
{ try {
[Link]();
// Displaying the thread that is running }
}
[Link](Thread " + [Link]().getId() + " is }
running");
Output
} Thread 15 is running
catch (Exception e) {// Throwing an exception Thread 14 is running

[Link]("Exception is caught");
Thread 16 is running
Thread 12 is running
} }}
Thread 11 is running
// Main Class
Thread 13 is running
Thread 18 is running
Thread 17 is running
// Main Class
class Multithread {
2) Thread creation by implementing the Runnable
Interface public static void main(String[] args)
We create a new class which implements {
[Link] interface and override run() method. int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
// Java code for thread creation by implementing the Runnable Interface Thread object
= new Thread(new MultithreadingDemo());
class MultithreadingDemo implements Runnable { [Link]();
}} }
public void run()
Output
{ try {
Thread 13 is running
// Displaying the thread that is running Thread 11 is running
[Link]( "Thread " + [Link]().getId() Thread 12 is running

+ " is running");
Thread 15 is running
Thread 14 is running
} catch (Exception e) { // Throwing an exception
Thread 18 is running
[Link]("Exception is caught"); }}}
Thread 17 is running
Thread 16 is running
public class TestThread {
public static void main(String args[]) {
ThreadDemo thread1 = new ThreadDemo( "Thread-1");
ThreadDemo thread2 = new ThreadDemo( "Thread-2");
[Link]();
Ex. Create a Thread by Extending a Thread Class [Link]();
class ThreadDemo extends Thread { }
ThreadDemo( String name) { } OUTPUT:
super(name); Thread: Thread-1, State: New
[Link]("Thread: " + name + ", " + "State: New"); Thread: Thread-2, State: New
} Thread: main, State: Start
public void run() { Thread: main, State: Start
[Link]("Thread: " + [Link]().getName() + ", " + "State: Running");Thread: Thread-1, State: Running
for(int i = 4; i > 0; i--) { Thread: Thread-2, State: Running
Thread: Thread-1, 4
[Link]("Thread: " +[Link]().getName() + ", " + i); Thread: Thread-2, 4
} Thread: Thread-1, 3
[Link]("Thread: " + [Link]().getName() + ", " + "State: Dead"); Thread: Thread-2, 3
} Thread: Thread-1, 2
public void start () { Thread: Thread-2, 2
[Link]("Thread: " + [Link]().getName() + ", " + "State: Start"); Thread: Thread-1, 1
[Link](); Thread: Thread-2, 1
} Thread: Thread-1, State: Dead
} Thread: Thread-2, State: Dead
Ex. Create a Thread by Implementing a Runnable Interface
class RunnableDemo implements Runnable { OUTPUT:
private String threadName; Thread: Thread-1, State: New
RunnableDemo( String name) { Thread: Thread-2, State: New
threadName = name; Thread: Thread-2, State: Running
[Link]("Thread: " + threadName + ", " + "State: New"); Thread: Thread-1, State: Running
} Thread: Thread-2, 4
public void run() { Thread: Thread-1, 4
[Link]("Thread: " + threadName + ", " + "State: Running"); Thread: Thread-2, 3
for(int i = 4; i > 0; i--) { Thread: Thread-1, 3
[Link]("Thread: " + threadName + ", " + i); Thread: Thread-2, 2
} Thread: Thread-1, 2
[Link]("Thread: " + threadName + ", " + "State: Dead"); Thread: Thread-2, 1
} Thread: Thread-1, 1
} Thread: Thread-2, State: Dead
public class TestThread { Thread: Thread-1, State: Dead
public static void main(String args[]) {
RunnableDemo runnableDemo1 = new RunnableDemo( "Thread-1");
RunnableDemo runnableDemo2 = new RunnableDemo( "Thread-2");
Thread thread1 = new Thread(runnableDemo1);
Thread thread2 = new Thread(runnableDemo2);
[Link]();
[Link](); }}
Thread Class vs Runnable Interface
• If we extend the Thread class, our class cannot extend any other class because Java doesn’t support
multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base
classes.

• We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt
methods like yield() (forcing a processor to relinquish control of the current running thread), interrupt()
(calling the interrupt() method on the thread, breaks out the sleeping or waiting state) etc. that are not
available in Runnable interface.

• Using runnable will give you an object that can be shared amongst multiple threads.
Thread priorities
Here Threads will have priorities ranging from 1 to 10 and 3 constants are defined as follows:

• public static int NORM_PRIORITY

• public static int MIN_PRIORITY

• public static int MAX_PRIORITY

Inbuild Methods of Thread Class


• currentThread() method
• setName() method
• getName() method
How to get and set priority of a thread in java.

• public final int getPriority(): [Link]() method returns priority of given thread.

• public final void setPriority(int newPriority): [Link]() method changes the priority
of thread to the value newPriority.
// Java Program to Illustrate Priorities
in Multithreading [Link]("t2 thread priority : " + [Link]());
import [Link].*; [Link]("t3 thread priority : " + [Link]());
// Main class // Setting priorities of above threads by passing integer arguments
class ThreadDemo extends Thread { [Link](2);
public void run() [Link](5);

{ [Link]("Inside run method"); [Link](8);


// [Link](21); will throw IllegalArgumentException
}
// 2
public static void main(String[] args)
[Link]("t1 thread priority : "+ [Link]());
{// Creating random threads with the help of above class
// 5
ThreadDemo t1 = new ThreadDemo();
[Link]("t2 thread priority : " + [Link]());
ThreadDemo t2 = new ThreadDemo();
// 8 }
ThreadDemo t3 = new ThreadDemo();
// Display the priority of above thread
[Link]("t1 thread priority : " + [Link]());
[Link]("t3 thread priority : " + [Link]());

// Main thread Displays the name of currently executing Thread

[Link]( "Currently Executing Thread : "+[Link]().getName());

[Link]( "Main thread priority : " + [Link]().getPriority());


Output
// Main thread priority is set to 10 t1 thread priority : 5
t2 thread priority : 5
[Link]().setPriority(10);
t3 thread priority : 5
[Link]( "Main thread priority : “ + [Link]().getPriority()); t1 thread priority : 2
t2 thread priority : 5
}
t3 thread priority : 8
Currently Executing Thread : main
Example: Java Program to illustrate Creation and execution of a Main thread priority : 5
thread via start() and run() method in Single inheritance Main thread priority : 10
Synchronizing Threads
The main reason for using thread synchronization are as follows:

 To prevent interference between threads.

 To prevent the problem of consistency.

Types of Thread Synchronization

In Java, there are two types of synchronization:

• Process synchronization

• Thread synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Understanding the problem without Synchronization
(In this example, there is no synchronization, so output is inconsistent.)
class Table{
} class MyThread2 extends Thread{
void printTable(int n) Output:
Table t; 5
{//method not synchronized 100
MyThread2(Table t){ 10
for(int i=1;i<=5;i++) 200
{ [Link](n*i); this.t=t; 15
300
try{ [Link](400); } }public void run(){ 20
400
catch(Exception e) [Link](100); } } 25
{[Link](e);} 500
class TestSynchronization1{
} } }
public static void main(String args[])
class MyThread1 extends Thread{
{ Table obj = new Table();
Table t;
MyThread1 t1=new MyThread1(obj);
MyThread1(Table t){
this.t=t; } MyThread2 t2=new MyThread2(obj);
public void run(){ [Link](); [Link](); } }
class MyThread1 extends Thread{
Synchronized Method Table t;
Synchronized method is used to lock an object for any MyThread1(Table t){
shared resource. this.t=t;
}
When a thread invokes a synchronized method, it
public void run(){
automatically acquires the lock for that object and
releases it when the thread completes its task. [Link](5);
}
Syntax:synchronized public void }
methodName() { } class MyThread2 extends Thread{
//example of java synchronized method Table t;
MyThread2(Table t){
public class TestSynchronization2{
class Table{
this.t=t; public static void main(String args[]){
synchronized void printTable(int n) } Table obj = new Table();//only one object
{//synchronized method public void run(){ MyThread1 t1=new MyThread1(obj);
for(int i=1;i<=5;i++){ [Link](100);
MyThread2 t2=new MyThread2(obj);
[Link](n*i); }
try{ } [Link](); Output:
[Link](400); [Link](); 5 10 15 20 25
}catch(Exception e){[Link](e);} } 100 200 300 400 500
} } } }
Synchronized Block Syntax:synchronized (object reference)
{ // Insert code here}
class Table
• Synchronized block is used to lock an object
for any shared resource. { void printTable(int n){
• Scope of synchronized block is smaller than
synchronized(this) {
the method.
• A Java synchronized block doesn't allow //This is a synchronized block
more than one JVM, to provide access
control to a shared resource. for(int i=1;i<=5;i++){

• The system performance may degrade [Link](n*i);


because of the slower working of
synchronized keyword. try{ [Link](400);
• Java synchronized block is more efficient than }catch(Exception e){[Link](e);}
Java synchronized method.
} }}//end of the synchronized block }}
class MyThread1 extends Thread{
Output:
Table t;
5
MyThread1(Table t){ public class TestSynchronizedBlock1{
10
this.t=t;} public static void main(String args[]){
15
Table obj = new Table();
public void run(){
20
MyThread1 t1=new MyThread1(obj);
[Link](5); MyThread2 t2=new MyThread2(obj); 25

} [Link](); 100

class MyThread2 extends Thread{ [Link](); } }


200

Table t; 300

MyThread2(Table t){ 400

this.t=t; 500

} public void run(){

[Link](100); } }
class Table

Static Synchronization {
synchronized static void printTable(int n){
The method is declared static in this case. for(int i=1;i<=10;i++){
[Link](n*i);
It means that lock is applied to the class instead of an object try{
and only one thread will access that class at a time. [Link](400);
}catch(Exception e){}
In this example we have used synchronized keyword on the } }}
static method to perform static synchronization. class MyThread1 extends Thread{
Syntax:static synchronized returnType nameOfMethod( public void run(){
Type parameters) { // code } [Link](1);
We don't want interference between t1 and t3 or t2 and t4 bcoz } }
of diff locks. Static synchronization solves this problem. class MyThread2 extends Thread{
public void run(){
[Link](10);
} }
Output:
class MyThread3 extends Thread{ 1
2
public void run(){ 3
4
[Link](100); 5
6
} 7
8
} 9
10
class MyThread4 extends Thread{ 10
20
public void run(){ 30
40
[Link](1000); 50
60
} 70
80
} 90
100
public class TestSynchronization4{ 100
200
public static void main(String t[]){ 300
400
MyThread1 t1=new MyThread1(); 500
600
MyThread2 t2=new MyThread2(); 700
MyThread3 t3=new MyThread3(); 800
900
MyThread4 t4=new MyThread4(); 1000
1000
[Link](); 2000
3000
[Link](); 4000
5000
[Link](); 6000
7000
[Link](); 8000
9000
} } 10000
Interthread Communication
• It is implemented by following methods
of Object class:
o wait()

Method Description

public final void It waits until object is


wait()throws notified.
InterruptedException

public final void It waits for the specified


wait(long amount of time.
timeout)throws
InterruptedException
o notify()
Syntax: public final void notify() : It wakes
up one single thread called wait() on the same
object .
o notifyAll()
Syntax: public final void notifyAll() :It
wakes up all the threads called wait() on the
same object.
Difference between wait and sleep

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is completed.
methods(belong to the Object class)
Ex. of Inter Thread Communication in Java
synchronized void deposit(int amount){
class Customer{ [Link]("going to deposit...");
int amount=10000; [Link]+=amount;
[Link]("deposit completed... ");
synchronized void withdraw(int amount){ notify();
[Link]("going to withdraw..."); }}
if([Link]<amount){ class Test{
public static void main(String args[]){
[Link]("Less balance; waiting for deposit..."); final Customer c=new Customer();
Thread t = new Thread() {
try{wait();}
//Note: This creates a new anonymous subclass of the
catch(Exception e){ } Thread class.
} public void run() { [Link](15000); }};
[Link]();
[Link]-=amount;
Thread t = new Thread()
[Link]("withdraw completed..."); { public void run() { going to withdraw...
Less balance;
} [Link](10000); waiting for deposit...
}}; going to deposit...
deposit completed..
[Link]();}} withdraw completed
//Producer-Consumer problem ---> Inter Thread
Communication. catch(InterruptedException ie)
class Buffer {
{ [Link]("Exception Caught " +ie);
int item; }
boolean produced = false; }
synchronized void produce(int x) [Link]("Consumer - Consumed " +item);
{ produced = false;
if(produced) notify(); return item;
{ }
try{wait();} }
catch(InterruptedException ie) class Producer extends Thread
{ {
[Link]("Exception Caught"); Buffer b;
}} Producer( Buffer b)
item =x; {this.b = b;
[Link]("Producer - Produced-->" +item); start();}
produced =true; public void run()
notify();} {
synchronized int consume() [Link](10);
{ [Link](20);
if(!produced) [Link](30);
{ [Link](40);
try{wait();} [Link](50);}}
class Consumer extends Thread
{
Buffer b;
Consumer(Buffer b)
{this.b = b;
OUTPUT
start();}
public void run()
{
Producer - Produced-->10
[Link](); Consumer - Consumed 10
[Link]();
[Link](); Producer - Produced-->20
[Link]();
// [Link](); Consumer - Consumed 20
// [Link](); Producer - Produced-->30
// [Link]();
}} Consumer - Consumed 30
public class PCDemo
{public static void main(String args[]) Producer - Produced-->40
{
Buffer b = new Buffer(); //Synchronized Object
Consumer - Consumed 40
Producer p = new Producer(b); Producer - Produced-->50
Consumer c = new Consumer(b);
}}
The two methods of Thread class are
isAlive( ) method returns true if the thread upon which it is called is still
running, otherwise it returns false.
final boolean isAlive( )

join() method waits until the thread on which it is called terminates. The
calling thread waiting until the specified thread joins it.
final void join( ) throws InterruptedException

This method when called from the parent (main) thread makes parent
thread wait till child thread terminates.
final void join( long msec ) throws InterruptedException

To specify a maximum amount of time that we want to wait for the


specified thread to terminate.
//Program to Demonstarte isAlive() and join() public class JoinDemo
{
class NewThread implements Runnable { public static void main(String args[])
String name; {[Link]("The main Thread Started");
NewThread ob1 = new NewThread("One");
Thread t;
NewThread ob2 = new NewThread("Two");
NewThread(String tname) NewThread ob3 = new NewThread("Three");
{ name = tname; [Link]("Thread One is alive: "+ [Link]());
[Link]("Thread Two is alive: "+ [Link]());
t = new Thread(this, name);
[Link]("Thread Three is alive: "+ [Link]());
[Link]("New thread: " + t); // wait for threads to finish
[Link](); } [Link]("Waiting for child threads to finish.");
try {
public void run() { [Link](); One
Main
try {for(int i = 5; i > 0; i--) [Link]();
thread(t)
{ [Link](name + ": " + i); [Link](); Two
}
[Link](1000);} catch (InterruptedException e)
{ [Link]("Main thread Interrupted"); Three
}
}
catch (InterruptedException e)
[Link]("Thread One is alive: "+ [Link]());
{ [Link](name + " interrupted."); [Link]("Thread Two is alive: "+ [Link]());
} [Link]("Thread Three is alive: "+ [Link]());
[Link]("Main thread Completed.");
[Link](name + "Completed" );}}
}}
OUTPUT:
Three: 3
The main Thread Started
One: 3
New thread: Thread[#32,One,5,main]
Two: 2
New thread: Thread[#33,Two,5,main]
Three: 2
New thread: Thread[#34,Three,5,main]
One: 2
Thread One is alive: true
Two: 1
Thread Two is alive: true
Three: 1
Thread Three is alive: true
One: 1
Waiting for child threads to finish.
TwoCompleted
Two: 5
OneCompleted
One: 5
ThreeCompleted
Three: 5
Thread One is alive: false
Three: 4
Thread Two is alive: false
Two: 4
Thread Three is alive: false
One: 4
Main thread Completed.
Two: 3
//Program to use isAlive() and join() – extending Thread class public class JoinDemo1
class NewThread extends Thread {
{ public static void main(String args[])
String name; {
NewThread(String tname) [Link]("The main Thread Started");
{ NewThread t1 = new NewThread("One");
name=tname; NewThread t2 = new NewThread("Two");
start(); NewThread t3 = new NewThread("Three");
} [Link]("Thread One is alive: "+ [Link]());
public void run() [Link]("Thread Two is alive: "+ [Link]());
{ [Link]("ThreadThree is alive: "+ [Link]());
try // wait for threads to finish
{ [Link]("Waiting for child threads to finish.");
for(int i = 5; i > 0; i--) try {[Link]();
{ [Link](name + ": " + i); [Link]();
[Link](1000); [Link]();
} }
} catch (InterruptedException e)
catch (InterruptedException e) { [Link]("Main thread Interrupted");
{ [Link](name + " interrupted."); }
} [Link]("Thread One is alive: "+ [Link]());
[Link](name + "Completed" ); [Link]("Thread Two is alive: "+ [Link]());
} [Link]("Thread Threeis alive: "+ [Link]());
} [Link]("Main thread Completed.");}}
OUTPUT:
The main Thread Started One: 2
Thread One is alive: true Two: 2
Thread Two is alive: true Three: 1
ThreadThree is alive: true One: 1
Two: 5 Two: 1
One: 5 ThreeCompleted
Three: 5 OneCompleted
One: 4 TwoCompleted
Three: 4 Thread One is alive: false
Two: 4 Thread Two is alive: false
One: 3 Thread Threeis alive: false
Three: 3 Main thread Completed
Two: 3
Three: 2
Ex. java program on creation of 2 threads one will display even
numbers and another will display odd numbers
class EvenThread extends Thread { public class EvenOddThreads {
public void run() { public static void main(String[] args) {
for (int i = 0; i <= 10; i++) { EvenThread even = new EvenThread();
if (i % 2 == 0) { OddThread odd = new OddThread();
[Link]("Even Thread: " + i);
try { [Link](); // starts even thread
[Link](500); // pause for clarity [Link](); // starts odd thread
} catch (InterruptedException e) { }
[Link](e); }
} } } OUTPUT: Even Thread: 0
} } Odd Thread: 1
class OddThread extends Thread { Odd Thread: 3
public void run() { Even Thread: 2
for (int i = 0; i <= 10; i++) { Odd Thread: 5
if (i % 2 != 0) { Even Thread: 4
[Link]("Odd Thread: " + i); Odd Thread: 7
try { Even Thread: 6
[Link](500); Odd Thread: 9
} catch (InterruptedException e) { Even Thread: 8
[Link](e); Even Thread: 10
} } } } }
public class ThreadPriorityDemo {
Ex. write java program to create 2 threads with name one and public static void main(String[] args) {
two . Write a driver class and assign priorities to threads such MyThread t1 = new MyThread("one");
that thread two executes first before one. MyThread t2 = new MyThread("two");
// Set priorities
class MyThread extends Thread { [Link](Thread.MIN_PRIORITY); // Lowest priority = 1
[Link](Thread.MAX_PRIORITY);// Highest priority = 10
public MyThread(String name) { // Start threads
super(name); // set thread name [Link]();
} [Link]();
}
public void run() { }
for (int i = 1; i <= 5; i++) { OUTPUT :
[Link]("Thread " + getName() + " is running: " + i); Thread one is running: 1
try { Thread two is running: 1
[Link](500); // just to slow down output Thread two is running: 2
} catch (InterruptedException e) { Thread one is running: 2
[Link](e); Thread two is running: 3
} Thread one is running: 3
} Thread two is running: 4
} Thread one is running: 4
} Thread two is running: 5
Thread one is running: 5
UNIT TEST III
1. Explain the different types of exceptions and the exception hierarchy in
java with appropriate examples.
2. Write a program to generate an exception whenever user input is odd
number less than 50.
3. Summarize the following with example program
4. i. ArithmeticException
5. ii. ArrayOutOfBoundsException
6. Describe the creation of a single thread and multiple threads using an
example.
7. Create a Bank database application program to illustrate the use of
multithreads.
8. With a neat sketch ,explain the life cycle of thread in java.
9. What is Priority? Explain thread priorities in detail.
10. Write a Java program to demonstrate thread synchronization.
11. Outline the Thread Class and write about its associated in built methods.

You might also like