0% found this document useful (0 votes)
13 views41 pages

OOPJ Module-3

The document covers Exception Handling and Multithreading in Java, detailing concepts, types of exceptions, and keywords used in exception handling such as try, catch, throw, and finally. It explains the difference between checked and unchecked exceptions, provides examples of common exceptions, and discusses the structure of try-catch blocks, including nested try blocks and the use of finally. Additionally, it introduces multithreading concepts, including thread life cycles, synchronization, and inter-thread communication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views41 pages

OOPJ Module-3

The document covers Exception Handling and Multithreading in Java, detailing concepts, types of exceptions, and keywords used in exception handling such as try, catch, throw, and finally. It explains the difference between checked and unchecked exceptions, provides examples of common exceptions, and discusses the structure of try-catch blocks, including nested try blocks and the use of finally. Additionally, it introduces multithreading concepts, including thread life cycles, synchronization, and inter-thread communication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 3 Exception Handling and Multithreading

Exception Handling: Concepts of exception handling, Types of exceptions,


Usage of try, catch, throw, throws and finally keywords, Built-in exceptions,
Creating user defined exceptions;

Multithreading: Concepts of multithreading, Differences between process


and thread, Thread life cycle, Creating multiple threads using Thread class
and Runnable interface, Synchronization,
Thread priorities, Inter thread communication.

Exception Handling

Exception:
 Exception is an abnormal condition that arises in a code sequence at a run

time and disrupts the normal flow of the program.


 It can be caught and handled by program or code.
 An object is created when an exception occurs. This object is called
exception object and contains information like, name and description of
exception along with the state of the program.
 There is always a reason behind an exception. Following are the reason why
exception can occur in the code:
 Invalid input of the users
 Failure of device
 Weak network connection
 Limitation of resources
 Errors in code (syntax or logical error)
 Opening a file that is unavailable

Page | 1
Types of Exceptions:
 There are two types of exceptions in java:
1. Checked exceptions (95% of exceptions in java are checked):
2. Unchecked exceptions (5% of exceptions in java are unchecked)

Page | 2
1. Checked Exceptions
 The exceptions that are checked at compilation time by the Java compiler

are called checked exceptions.


 In case of checked exceptions, the programmer should either handle
them or throw t h e m without handling them.
 The programmer cannot ignore checked exceptions as Java compiler will
remind of the exception until taken care of.
 Example:

Excepti Descripti
on on
IOExcepion IO activity could not be performed.
ClassNotFoundException Class not found exception
IIlegalAccessException Access to a class is denied

2. Unchecked Exceptions
3.
 The exceptions that are checked by the JVM at runtime are called
unchecked exceptions.
 Programmers can write a java program with unchecked exceptions and
can compile the program.
 Programmer can see their effect only when he/she runs the program.
 Example:

Excepti Descripti
on on
ArithmeticException Arithemetic eror, such as divide by
zero
ArrayIndexOutOfBoundsExc Array index is out of bound
eption
NegativeArraySizeException Array created with a negative size

NullPointerException Invalid use of null reference

NumberFormatException Invalid conversion of a string to a


numeric format
Page | 3
Exception Hierarchy:

Object Class:
 Object class is present in [Link] package.
 Every class in Java is directly or indirectly derived from the Object class.
 If a class does not extend any other class, then it is a direct child class of Object

and if extends another class then it is indirectly derived.


 Therefore, the Object class methods are available to all Java classes.
 Hence Object class acts as a root of the inheritance hierarchy in any Java
Program.
Page | 4
Throwable Class:
 The Throwable class is the superclass of every error and exception in the Java
language.
 Only objects that are one of the subclasses of this class are thrown by any “Java

Virtual Machine” or may be thrown by the Java throw statement.


 For the motives of checking exceptions during compile-time, Throwable and any
subclass of Throwable which is not also a subclass of either Error or
RuntimeException are considered as checked exceptions.
 Throwable class is the root class of Java Exception Hierarchy and is inherited by
two subclasses:
1. Exception
2. Error
Exception Handling:
 Exception handling helps program to prevent abnormal crashing.
 Whenever an exception occurs inside a method, an exception object is

created by a method and is handed over to the JVM, this is called default
exception handling.
 There are 5 keywords used in java exception handling:
1. try
2. catch
3. finally
4. throw
5. throws

Page |05
Keyword Description
 The "try" keyword is used to specify a block where we
try 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.
 The "finally" block is used to execute the
finally 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.

 The "throws" keyword is used to declare exceptions.


throws  It specifies that there may occur an exception in the
method. It doesn't throw an exception. It is always
used with method signature.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

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

1. String s=null;
2. [Link]([Link]());//NullPointerException
3) A scenario where NumberFormatException occurs

Page |05
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.

1. String s="abc";
2. int i=[Link](s);//NumberFormatException
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.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block


Java try block

Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }finally{}
Java catch block

Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,

Page |05
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block
with a single try block.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1

[Link]

1. public class TryCatchExample1 {


2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. [Link]("rest of the code");
8.
9. }
10.
11.}
Test it Now

Output:

Exception in thread "main" [Link]: / by zero


Solution by exception handling

Let's see the solution of the above problem by a java try-catch block.

Example 2

[Link]

1. public class TryCatchExample2 {


2. public static void main(String[] args) {
3. try
4. {

Page |05
5. int data=50/0; //may throw exception
6. }
7. //handling the exception
8. catch(ArithmeticException e)
9. {
10. [Link](e);
11. }
12. [Link]("rest of the code");
13. }
14.
15.}
Test it Now

Output:

[Link]: / by zero
rest of the code

java Catch Multiple Exceptions


Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example 1

Let's see a simple example of java multi-catch block.

[Link]

1. public class MultipleCatchBlock1 {


2.

Page |05
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }
23.}
Test it Now

Output:

Arithmetic Exception occurs


rest of the code

Example 2

[Link]

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];

Page |05
7.
8. [Link](a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. [Link]("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. [Link]("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. [Link]("Parent Exception occurs");
21. }
22. [Link]("rest of the code");
23. }
24.}
Test it Now

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code
.
Java Nested try block

In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.

Page |05
[Link]
1. public class NestedTryBlock{
2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. [Link]("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. [Link](e);
14. }
15. //inner try block 2
16. try{
17. int a[]=new int[5];
18. //assigning the value out of array bounds
19. a[5]=4;
20. }
21. //catch block of inner try block 2
22. catch(ArrayIndexOutOfBoundsException e)
23. {
24. [Link](e);
25. }
26. [Link]("other statement");
27. }
28. //catch block of outer try block
29. catch(Exception e)
30. {
31. [Link]("handled the exception (outer catch)");
32. }
33. [Link]("normal flow..");
34. }
35.}
Output:

Page |05
Java finally block

Java finally block is a block used to execute important code such as closing the
connection, [Link] finally block is always executed whether an exception is handled or
not. Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.

The finally block follows the try-catch block.

o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.
o
o public class TestFinallyBlock1{
o public static void main(String args[]){
o
o try {
o
o [Link]("Inside the try block");
o
o //below code throws divide by zero exception
o int data=25/0;
o [Link](data);
o }
o //cannot handle Arithmetic type exception
o //can only accept Null Pointer type exception
o catch(NullPointerException e){
o [Link](e);
o }
o
o //executes regardless of exception occured or not
o finally {
o [Link]("finally block is always executed");
Page |05
o }
o
o [Link]("rest of the code...");
o
o }
o }

Outp

[Link]

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3.
4. try {
5.
6. [Link]("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. [Link](data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. [Link]("Exception handled");
16. [Link](e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {

Page |05
21. [Link]("finally block is always executed");
22. }
23.
24. [Link]("rest of the code...");
25. }
26. }

Output:

java throw keyword

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related to
user inputs, servers, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in
this section.

We can also define our own set of conditions and throw an exception explicitly using the
throw keyword. For example, we can throw an ArithmeticException if we divide a
number by another number. Here, we just need to set the condition and throw the
exception using the throw keyword i.e., for user defined exceptions.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");

Page |05
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the subclass of Throwable and the user-defined exceptions usually extend
the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

[Link]

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

1. public class TestThrow1 {


2.
3. //function to check if person is eligible to vote or not
4. public static void validate(int age) {
5. if(age<18) {
6. //throw Arithmetic exception if not eligible to vote
7. throw new ArithmeticException("Person is not eligible to vote");
8. }
9. else {
10. [Link]("Person is eligible to vote!!");
11. }
12. }
13. //main method
14. public static void main(String args[]){
15. //calling the function
16. validate(13);
17. [Link]("rest of the code...");
18. }
19.}

Output:

Page |05
1. public class TestThrow {
2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square
");
6. }
7. else {
8. [Link]("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. [Link](-3);
15. [Link]("Rest of the code..");
16. }
17.}

Output:

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to
provide the exception handling code so that the normal flow of the program can be
maintained.
Page |05
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is the programmer's fault that he
is not checking the code before it is used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.

[Link]

1. import [Link];
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{ m(); }
7. void p(){
8. try{
9. n();
10. }catch(Exception e){[Link]("exception handled");}
11. }
12. public static void main(String args[]){
13. Testthrows1 obj=new Testthrows1();
14. obj.p();
15. [Link]("normal flow...");
16. }
17.}
Test it Now

Output:

exception handled
normal flow...

[Link]

Page |05
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. [Link]();
12. }catch(Exception e){[Link]("exception handled");
13.}
14. [Link]("normal flow...");
15. }
16.}
Test it Now

Output:

exception handled
normal flow...

Differences Between throw vs throws:

Sr. throw throws


no.
1. Java throw keyword is used throw Java throws keyword is used in the
method signature to declare an
an exception explicitly in the code, exception which might be thrown by the
inside the function or the block of function while the execution of the
code. code.
2. Type of exception Using throw Using throws keyword, we can declare
keyword, we can only propagate both checked and unchecked
unchecked exception i.e., the exceptions. However, the throws
checked exception keyword can be used to propagate
cannot be propagated using throw checked
only. exceptions only.
3. The throw keyword is followed by The throws keyword is followed by
an class names
instance of Exception to be thrown. of Exceptions to be thrown.

Page |05
4. throw is used within the method. throws is used with the method
signature.
5. We are allowed to throw only one We can declare multiple exceptions
exception at a time i.e. we cannot using throws keyword that can be
throw multiple exceptions. thrown by the method. For example,
main() throws IOException,
SQLException.

Difference between final, finally and finalize

Sr. Key final finally finaliz


no. e
1. Definition final is the keyword finally is the block in finalize is the method
and access modifier Java Exception in Java which is used
which is used to apply Handling to execute to perform clean up
restrictions on a class, the important code processing just
method or variable. whether the before object is
exception occurs or garbage collected.
not.
2. Applicabl Final keyword is used finally block is always finalize() method is
e to with the classes, related to the try and used with the objects.
methods and catch block in
variables. exception
handling.
3. Functionali (1) Once declared, (1) finally block runs finalize method
ty final variable the important code performs the
becomes constant even if exception cleaning activities
and cannot be occurs or not. with respect to the
modified. (2) finally block cleans object before its
(2) final method up all the resources destruction.
cannot be overridden used in try block
by sub class.
(3) final class cannot
be inherited.
4. Execution Final method is finally block is finalize method is
executed as executed
executed only when
soon as the try-catch just before the object
we call it.
block is executed. is destroyed.

Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries.
These exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java.
1. ArithmeticException:
It is thrown when an exceptional condition has occurred in an arithmetic

Page |05
operation.
2. ArrayIndexOutOfBounds Exception:
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.
3. ClassNotFoundException:
This Exception is raised when we try to access a class whose definition is
not found.
4. NullPointerException:

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.
5. NoSuchMethodException:

It is thrown when accessing a method that is not found.


User-defined exception:
 Creating our own Exception is known as custom exception or user-defined
exception.
 In Java, we can create our own exceptions that are derived classes of the
Exception class.
 Create User-Defined Exceptions:
o To create a custom exception in Java, we have to create a class by
extending it with an Exception class from the [Link] package.
o Below is the template to be followed for creating a user-defined exception
in java.
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10. // class that uses custom exception InvalidAgeException
11. public class TestCustomException1
12. {
13.
14. // method to check the age
15. static void validate (int age) throws InvalidAgeException{
16. if(age < 18){
Page |05
17.
18. // throw an object of user defined exception
19. throw new InvalidAgeException("age is not valid to vote");

20. }
21. else {
22. [Link]("welcome to vote");
23. }
24. }
25.
26. // main method
27. public static void main(String args[])
28. {
29. try
30. {
31. // calling the method
32. validate(13);
33. }
34. catch (InvalidAgeException ex)
35. {
36. [Link]("Caught the exception");
37.
38. // printing the message from InvalidAgeException object

39. [Link]("Exception occured: " + ex);


40. }
41.
42. [Link]("rest of the code...");
43. }
44. }

Output:

public class SimpleCustomException extends Exception{

Page |05
Multithreading
Process -- Definition:
A process is a program in execution.

Program VS Process:
 A program is a passive entity, such as a file containing a list of instructions stored

on disk (also called an executable file).


 A process is an active entity, with a program counter specifying the next instruction
to execute and a set of associated resources.

Thread - Definition:
A thread is an extremely lightweight process, or the smallest component of the
process, that enables software to work more effectively by doing numerous tasks
concurrently.

Difference Table Between Process and Thread

Process Thread

Page |05
A process is an instance of a program Thread is a segment of a process or a
that is being executed or processed. lightweight process that is managed by the
scheduler independently.

Processes are independent of each Threads are interdependent and share


other and hence don't share a memory memory.
or other resources.

Each process is treated as a new The operating system takes all the user-level
process by the operating system. threads as a single process.

If one process gets blocked by the If any user-level thread gets blocked, all of its
operating system, then the other peer threads also get blocked because OS
process can continue the execution. takes all of them as a single process.

Context switching between two Context switching between the threads is fast
processes takes much time as they are because they are very lightweight.
heavy compared to thread.

The data segment and code segment Threads share data segment and code
of each process are independent of the segment with their peer threads; hence are
other. the same for other threads also.

The operating system takes more time Threads can be terminated in very little time.
to terminate a process.

Multithreading:
Multithreading is a process of executing multiple threads simultaneously.

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.
Thread Life Cycle:
In Java, a thread always exists in any one of the following states. These states
are:
1. New
2. Runnable

Page |05
3. Running
4. Blocked (Non-runnable state)
5. Dead

Page |05
1. New (Newborn State): When we create a thread object using Thread class, thread
is born and is known to be in Newborn state. That is, when a thread is born, it
enters into new state but the start() method has not been called yet on the
instance.
2. Runnable state: Runnable state means a thread is ready for execution. When the
start() method is called on a new thread, thread enters into a runnable state.
In runnable state, thread is ready for execution and is waiting for availability of
the processor (CPU time). That is, thread has joined queue (line) of threads that
are waiting for execution.
If all threads have equal priority, CPU allocates time slots for thread execution on the
basis of first-come, first-serve manner. The process of allocating time to threads is
known as time slicing. A thread can come into runnable state from running, waiting,
or new states.
3. Running state: Running means Processor (CPU) has allocated time slot to
thread for its execution. When thread scheduler selects a thread from the
runnable state for execution, it goes into running state.
In running state, processor gives its time to the thread for execution and executes
its run method. This is the state where thread performs its actual functions. A
thread can come into running state only from runnable state.
A running thread may give up its control in any one of the following situations and
can enter into the blocked state
a) When the sleep() method is invoked on a thread to sleep for the specified time
period, the thread is out of the queue during this period. The thread again reenters into
the runnable state as soon as this period is elapsed.
b) When a thread is suspended using the suspend() method for some time to satisfy
some conditions. A suspended thread can be revived by using resume() method.
c) When the wait() method is called on a thread to wait for some time. The thread in the
wait state can be re-run using notify() or notifyAll() method.
4. . Blocked state: A thread is considered to be blocked when it is suspended, sleeping,
or waiting for some time to satisfy some condition.
5. Dead state: A thread dies or moves into dead state automatically when its run()
method completes the execution of statements. That is, a thread is terminated or dead
when a thread comes out of run() method. A thread can also be dead when the stop()
method is called.
During the life cycle of thread in Java, a thread moves from one state to another state in
a variety of ways. This is because in multithreading environment, when multiple threads
are executing, only one thread can use CPU at a time. Page |
326
All other threads live in some other states, either waiting for their turn on CPU or
waiting for satisfying some conditions. Therefore, a thread is always in any of the five
states.

Main Thread:
When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of your program, because it is the one that is executed
when your program begins.
The main thread is important for
two reasons:
1. It is the thread from which other “child” threads will be spawned.
2. Often, it must be the last thread to finish execution because it performs

various shutdown actions.


Although the main thread is created automatically when your program is
started, it can be controlled through a Thread object. To do so, you must obtain a
reference to it by calling the method currentThread( ), which is a public static member
of Thread. Its general form is shown here:
static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you
have a reference to the main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:

public class MainThreadDemo {


public static void main(String[]args)
{
Thread t = [Link]();
[Link]("CurrenThred"+t);
}
}

Output:
Current Thread: Thread[main,5,main]

Page |
327
This displays, in order: the name of the thread, its priority, and the name of its
group. By default, the name of the main thread is main. Its priority is 5, which is the
default value, and main is also the name of the group of threads to which this thread
belongs.
The 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)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method
on the thread.
3. public void sleep(long milis

4. econds): Causes the currently executing thread to sleep (temporarily cease


execution) for the specified number of milliseconds.
5. public void join(): waits for a thread to die.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yie

15. ld(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
16. public void suspend(): is used to suspend the thread(depricated).
17. public void resume(): i8s used to resume the suspended thread(depricated).
18. public void stop(): is used to stop the thread(depricated).
Page |
328
The 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.

Creating Threads:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Creating Thread by extending Thread Class:


We can make our class runnable as thread by extending the class Thread. This
gives us access to all the thread methods directly.
Example:
Write a Java Program that creates a thread by extending Thread class.

1. class Multi extends Thread{


2. public void run(){
3. [Link]("thread is running...");
4. }
5. }
6. class Multi2 extends Thread{
7. public void run(){
8. [Link]("thread is running successfully...");
9. }
[Link] static void main(String args[]){
[Link] t1=new Multi();
12.Multi2 t2=new Multi();
[Link]();
[Link]();
15.
16. } Page |
329
17.}

Output:

thread is running...

Creating Thread by implementing Runnable Interface:


Example:
Write a Java Program that creates a thread by extending Runnable class.

2) Java Thread Example by implementing Runnable interface

FileName: [Link]

1. class Multi3 implements Runnable{


2. public void run(){
3. [Link]("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. [Link]();
10. }
11.}

Output:

thread is running...

Programs
Write a Java Program that creates a thread with a specified name, and print the
name and id of the thread.
Program:

public class ThreadExample {


public static void main(String[] args) {

// Create a new thread with a specified name


Thread myThread = new Thread(new MyRunnable(), "MyThread");
Page |
330
// Start the thread
[Link]();

// Get and print the name and id of the thread


long threadId = [Link]();
String threadName = [Link]();
[Link]("Thread Name: " + threadName);
[Link]("Thread ID: " + threadId);
}

static class MyRunnable implements Runnable {


@Override
public void run() {
// Task to be performed by the thread
[Link]("Thread is running...");
}
}
}
Output:
Thread Name: MyThread
Thread ID: 10
Thread is running...

Sleep()
thread Class is a class that is basically a thread of execution of the programs. It is
present in [Link] package. Thread class contains the Sleep() method. There are two
overloaded methods of Sleep() method present in Thread Class, one is with one
argument and another one is with two arguments. The sleep() method is used to stop
the execution of the current thread(whichever might be executing in the system) for a
specific duration of the time and after that time duration gets over, the thread which
is executing earlier starts to execute again.
Program:
Write a Java Program that creates 2 threads, each thread prints numbers from 1 to 5
and also each thread sleeps 500 milliseconds.
Description:
Use sleep( ) method to sleep a thread for the specified milliseconds of time.
Program:

public class ThreadExample {


public static void main(String[] args) { Page |
331
// Create and start two threads
Thread thread1 = new NumberPrinter("Thread 1");
Thread thread2 = new NumberPrinter("Thread 2");
[Link]();
[Link]();
}

static class NumberPrinter extends Thread {


public NumberPrinter(String name) {
super(name);
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](getName() + ": " + i);
try {
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}

Output:
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5

Thread priorities:

Each thread has a priority. Priorities are represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the threads according to their priority
Page |
332
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority

Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The [Link]() method returns the


priority of the given thread.

public final void setPriority(int newPriority): The [Link]() method


updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).

 Each thread has a priority. Priorities are represented by a number between 1


and 10.
 In most cases, thread schedular schedules the threads according to their
priority (known as preemptive scheduling).
 But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
 3 priority constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
 Default priority of a thread is 5 (NORM_PRIORITY).
 The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:

FileName: [Link]

1. // Importing the required classes


2. import [Link].*;
3.
4. public class ThreadPriorityExample extends Thread
5. {
6.
7. // Method 1
8. // Whenever the start() method is called by a thread
9. // the run() method is invoked
Page |
333
[Link] void run()
11.{
12.// the print statement
[Link]("Inside the run() method");
14.}
15.
16.// the main method
[Link] static void main(String argvs[])
18.{
19.// Creating threads with the help of ThreadPriorityExample class
[Link] th1 = new ThreadPriorityExample();
[Link] th2 = new ThreadPriorityExample();
[Link] th3 = new ThreadPriorityExample();
[Link]("Priority of the thread th1 is : " + [Link]());
[Link]("Priority of the thread th2 is : " + [Link]());
25. [Link]("Priority of the thread th2 is : " + [Link]());
26. [Link](6);
[Link](3);
[Link](9);
29. // 6
[Link]("Priority of the thread th1 is : " + [Link]());
31. // 3
[Link]("Priority of the thread th2 is : " + [Link]());
33. // 9
[Link]("Priority of the thread th3 is : " + [Link]());
35. // Main thread
36. // Displaying name of the currently executing thread
[Link]("Currently Executing The Thread : " +
[Link]().getName());

[Link]("Priority of the main thread is : " + [Link]().getPriorit


y());
40. // Priority of the main thread is 10 now
[Link]().setPriority(10);
[Link]("Priority of the main thread is : " + [Link]().getPriorit
y());
43.}
44.}

Output:

Priority of the thread th1 is : 5


Page |
334
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priorityofthemainthreadis:10

Page |
335
Synchronization in Java
 Synchronization in Java is the capability to control the access of multiple threads
to any shared resource.
 Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
 Synchronization in Java is the process that allows only one thread at a particular
time to complete a given task entirely.
 By default, the JVM gives control to all the threads present in the system to
access the shared resource, due to which the system approaches race condition.

Why use Synchronization


The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.

Understanding the concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
From Java 5 the package [Link] contains several lock
implementations.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see the
example:

Page |
436
In the above code, as you can see, both the statements are running simultaneously,
which creates an inconsistency in the program. Just using the synchronized keyword
Page |
437
before the method can easily solve this problem, as shown below.

Thread Synchronization:
There are two types of thread synchronization mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
2. Cooperation (Inter-thread communication)
Page |
438
1. Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
[Link] Method
[Link] Block
3. Static Synchronization
1. Synchronized method:
It is a method that can be declared synchronized using the keyword
“synchronized” before the method name. By writing this, it will make the code in a
method thread-safe so that no resources are shared when the method is executed.
Syntax:
synchronized public void methodName( ) { }
Synchronized Block:
If a block is declared as synchronized then the code which is written inside a
method is only executed instead of the whole code. It is used when sequential access
to code is required.
Syntax:
synchronized (object reference)
{
// Insert code here
}
Static Synchronization:
The method is declared static in this case. It means that lock is applied to the
class instead of an object and only one thread will access that class at a time.
Syntax:
synchronized static return_type method_name{ }

Inter Thread Communication


Inter thread communication in Java is a method that allows several threads to
communicate with one another. It provides an effective way for multiple threads to
communicate with each other by minimizing CPU idle time.

CPU idle time is a procedure that prevents CPU cycles from being wasted. When many
threads are running at the same time, they may need to communicate with one another
by sharing information. A thread exchanges data before or after changing its state.
Communication between threads is vital in a variety of cases.

Page |
439
For example; Assume there are two threads: A and B. Thread B executes its task using
the data developed by Thread A. Thread B would waste several CPU cycles while it waits
for Thread A to create data. On the other hand, threads A and B do not have to wait and
check each other's status every time they complete their tasks if they engage with each
other after they have finished their tasks, As a result, you would not waste CPU cycles
[Link] is implemented by following methods of Object class:

[Link]( )
[Link]( )
3. notifyAll( )
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.
Method Description
public final void wait( )throws It waits until object is notified.
InterruptedException
public final void wait(long timeout)throws It waits for the specified
InterruptedException amount of time.
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.
Syntax:
public final void notify( )

3. notifyAll()
method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll( )

Page |
440
Understanding the process of inter-thread communication:

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.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread
class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?

wait sleep
() ()
The wait() method releases the The sleep() method doesn't
lock. 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 notifiedby notify() or After the specified amount of
notifyAll() methods time, sleep is
completed

Page |
441

You might also like