0% found this document useful (0 votes)
10 views50 pages

Unit 3

This document covers Exception Handling and Multithreading in Java, detailing the basics of exception handling, types of exceptions, and the use of try, catch, and finally blocks. It explains the concept of multithreading, including thread creation, synchronization, and inter-thread communication. Additionally, it provides examples of built-in exceptions and demonstrates how to throw and catch exceptions in Java programming.

Uploaded by

adchuthan.cs22
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)
10 views50 pages

Unit 3

This document covers Exception Handling and Multithreading in Java, detailing the basics of exception handling, types of exceptions, and the use of try, catch, and finally blocks. It explains the concept of multithreading, including thread creation, synchronization, and inter-thread communication. Additionally, it provides examples of built-in exceptions and demonstrates how to throw and catch exceptions in Java programming.

Uploaded by

adchuthan.cs22
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
You are on page 1/ 50

CS3391-OOP-UNIT-3

UNIT III - EXCEPTION HANDLING AND MULTITHREADING


Exception Handling basics – Multiple catch Clauses – Nested try Statements –
Java’s Built-in Exceptions – User defined Exception. Multithreaded
Programming: Java Thread Model–Creating a Thread and Multiple Threads –
Priorities – Synchronization – Inter Thread Communication- Suspending –
Resuming and Stopping Threads –Multithreading. Wrappers – Auto boxing.

3.1. EXCEPTION HANDLING BASICS


The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound,
IO, SQL, Remote etc.
3.1.1 Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception.
The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions
1) Checked Exception
The checked exceptions are those exceptions which is checked by the compiler at
runtime e.g.IOException, SQLException etc.
2) Unchecked Exception
The Unchecked exceptions are not checked by the compiler at run time e.g. Arithmetic
Exception, NullPointerException, ArrayIndexOutOfBoundsException etc.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.

1 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.1.2. HIERARCHY OF JAVA EXCEPTION CLASSES

3.1.3 THROWING AND CATCHING EXCEPTION


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws

2 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

Java Try Block


Java try block is used to enclose the code that might throw an exception. It must be used
within the method.Java try block must be followed by either catch or finally block.
Syntax
try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{}
Catching Exceptions
A method catches an exception using a combination of the try and catchkeywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks like
the following −
Syntax
try
{
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it. Every trya block
should be immediately followed either by a catch block or finally block.
Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest

3 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This will produce the following result −
Output

3.2 MULTIPLE CATCH BLOCKS


A try block can be followed by multiple catch blocks. The syntax for multiple catch
blocks looks like the following −
Syntax
try {
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
} catch (ExceptionType2 e2)
{
// Catch block
} catch (ExceptionType3 e3)
{

4 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number
of them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
class Excep1
{
public static void main(String args[])
{
int i=10;
try
{
i=i/Integer.parseInt(args[0]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(Exception e1)
{
System.out.println(e1);
}
System.out.println("Value of i=" +i);
}
}

OUTPUT

5 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.3 Nested Try Statements


➢ The try block within a try block is called nested try block. Every inner try block
must have a corresponding catch blocks.If any inner try block does not does not
have a catch block then the outer try block catch statement will be executed.
Syntax
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}

Program

class Excep6
{
public static void main(String args[])
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}

try

6 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Output

Internal working of java try-catch block

7 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception. Using a finally block allows you to run
any cleanup-type statements that you want to execute, no matter what happens in the protected
code.
A finally block appears at the end of the catch blocks and has the following syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)

8 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Test it Now
Output:
5
finally block is always executed

Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);

9 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed

3.4.THROWING AND CATCHING EXCEPTIONS


The Throw Keyword
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.
Syntax
throw new ArithmeticException(“—“);
Program
class Throw
{
static void validage(int age)
{
if(age<18)
{
throw new ArithmeticException("Not valid to give vote");
}
else
{
System.out.println("Welcome to vote");
}
}
public static void main(String args[])
{
try
{
validage(Integer.parseInt(args[0]));
}
catch(ArithmeticException e)
{
System.out.println(e);
}

10 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

System.out.println("Testing Complete");
}
}

Output

The 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 normal flow can be maintained.
Syntax
return_type method_name() throws exception_class_name{
//method code
}

Program

class myexception extends Exception


{
myexception(String s)
{
super(s);
}
}
class Throws
{
static void validage(int age) throws myexception
{
if(age<18)
{
throw new myexception("Not valid to give vote");
}

11 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

else
{
System.out.println("Welcome to vote");
}
}
public static void main(String args[])
{
try
{
validage(Integer.parseInt(args[0]));
}
catch(myexception my)
{
System.out.println(my);
}
System.out.println("Testing Complete");
}
}
Output

3.4 JAVA’S BUILT-IN EXCEPTIONS

SI.NO. Java UnChecked Exceptions Defined Java Checked Exceptions Defined


in java.lang. in java.lang.
1. ArithmeticException ClassNotFoundException
Arithmetic error, such as divide-by- Class not found.
zero.
2. ArrayIndexOutOfBoundsException CloneNotSupportedException
Array index is out-of-bounds.

12 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

Attempt to clone an object that does


not implement the Cloneable
interface.
3. ArrayStoreException IllegalAccessException
Assignment to an array element of an Access to a class is denied.
incompatible type.
4. ClassCastException InstantiationException
Invalid cast. Attempt to create an object of an
abstract class or interface.
5. IllegalArgumentException InterruptedException
Illegal argument used to invoke a One thread has been interrupted by
method. another thread.
6. IllegalMonitorStateException NoSuchFieldException
Illegal monitor operation, such as A requested field does not exist.
waiting on an unlocked thread.
7. IllegalStateException NoSuchMethodException
Environment or application is in A requested method does not exist.
incorrect state.
8. IllegalThreadStateException
Requested operation not compatible
with the current thread state.
9. IndexOutOfBoundsException
Some type of index is out-of-bounds.
10. NegativeArraySizeException
Array created with a negative size.
11. NullPointerException
Invalid use of a null reference.
12. NumberFormatException
Invalid conversion of a string to a
numeric format.
13. SecurityException
Attempt to violate security.
14. StringIndexOutOfBounds

13 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

Attempt to index outside the bounds of


a string.
15. UnsupportedOperationException
An unsupported operation was
encountered.

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.
3.4.1 Examples of Built-in Exception:
1. Arithmetic exception: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
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.

14 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

// Java program to demonstrate


// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds
3. ClassNotFoundException : This Exception is raised when we try to access a class
whose definition is not found.
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal
{
}
class Geeks
{
}
class MyClass
{
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();

15 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

System.out.println("Class created for" + o.getClass().getName());


}
}
Output:
ClassNotFoundException
4. FileNotFoundException : This Exception is raised when a file is not accessible or does
not open.
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
{
public static void main(String args[])
{
try {

// Following file does not exist


File file = new File("E:// file.txt");

FileReader fr = new FileReader(file);


}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:
File does not exist
5. IOException : It is thrown when an input-output operation failed or interrupted
// Java program to illustrate IOException
import java.io.*;
class Geeks
{
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {

16 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

System.out.print((char)i);
}
f.close();
}
}
Output:
error: unreported exception IOException; must be caught or declared to be thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
// Java Program to illustrate
// InterruptedException
class Geeks {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}

Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
7. NoSuchMethodException : t is thrown when accessing a method which is not found.
// Java Program to illustrate
// NoSuchMethodException
class Geeks {
public Geeks()
{
Class i;
try {
i = Class.forName("java.lang.String");
try {
Class[] p = new Class[5];
}

17 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Geeks();
}
}
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
8. NullPointerException : This exception is raised when referring to the members of a
null object. Null represents nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}

18 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

}
Output:
NullPointerException..
9. NumberFormatException : This exception is raised when a method could not convert
a string into a numeric format.
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
10. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate
that an index is either negative than the size of the string.
// Java program to demonstrate
// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element

19 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException

3.5 USER DEFINED EXCEPTION


➢ Java provides us the facility to create our own exceptions which are basically
derived classes of Exception. Creating our own Exception is known as a custom
exception or user-defined exception.
➢ Basically, Java custom exceptions are used to customize the exception according to
user needs.
➢ In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’
keyword.
3.5.1 Example of java custom exception.

class myexception extends Exception

myexception(String s)

super(s);

class Throws

static void validage(int age) throws myexception

20 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

if(age<18)

throw new myexception("Not valid to give vote");

else

System.out.println("Welcome to vote");

public static void main(String args[])

try

validage(Integer.parseInt(args[0]));

catch(myexception my)

System.out.println(my);

System.out.println("Testing Complete");

21 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

OUTPUT

3.6 MULTITHREADED PROGRAMMING:


Multithreading

➢ Multithreading in java is a process of executing multiple threads simultaneously.


➢ A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
➢ However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context -
switching between the threads takes less time than process.
➢ Java Multithreading is mostly used in games, animation, etc.

Differences between Multithreading and Multitasking

➢ Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.

22 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

o A thread is lightweight.
o Cost of communication between the thread is low.
Note: At least one process is required for each thread

3.6.1 JAVA THREAD MODEL


Thread Life Cycle

➢ A thread can be in one of the five states. The life cycle of the thread in java is controlled
by JVM. The java thread states are as follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated

Fig 1. Thread Life Cycle

23 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

New
➢ The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
Runnable
➢ The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
Running
➢ The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
➢ This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
➢ A thread is in terminated or dead state when its run() method exits.

3.7 CREATING A THREAD AND MULTIPLE THREADS


➢ There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Java Thread Example by extending Thread class

class Multi extends Thread{


public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output:
thread is running...

24 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:
thread is running...

3.7.2 Creating Multiple Threads in Java

o Creating more than one thread to perform multiple tasks is called multithreading
in Java. In multiple threading programming, multiple threads are executing
simultaneously that improves the performance of CPU because CPU is not idle
if other threads are waiting to get some resources.
o Multiple threads share the same address space in the heap memory. Therefore,
It is good to create multiple threads to execute multiple tasks rather than creating
multiple processes.

25 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

Example Program
// Two threads performing same tasks at a time.
//By implementing Runnable Interface
class MultiThread implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("thread running is "+i);
}
}
public static void main(String args[])
{
MultiThread m1=new MultiThread();
Thread t1 =new Thread(m1);
Thread t2= new Thread(m1);
Thread t3= new Thread(m1);
t1.start();
t2.start();
t3.start();
}
}
OUTPUT

26 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.8 PRIORITIES
➢ Thread priority in Java is a number assigned to a thread that is used by Thread scheduler
to decide which thread should be allowed to execute.
➢ In Java, each thread is assigned a different priority that will decide the order
(preference) in which it is scheduled for running.
➢ Thread priorities are represented by a number from 1 to 10 that specifies the relative
priority of one thread to another.
➢ The default priority of a thread is 5. Thread class in Java also provides several priority
constants to define the priority of a thread. These are:
1. MIN_PRIORITY = 1
2. NORM_PRIORITY = 5
3. MAX_PRIORTY = 10
➢ Thread scheduler selects the thread for execution on the first-come, first-serve basis.
That is, the threads having equal priorities share the processor time on the first -come
first-serve basis.
➢ When multiple threads are ready for execution, the highest priority thread is selected
and executed by JVM.
➢ In case when a high priority thread stops, or enters the blocked state, a low priority
thread starts executing.
➢ If any high priority thread enters the runnable state, it will preempt the currently running
thread forcing it to move to the runnable state. Note that the highest priority thread
always preempts any lower priority thread.
3.8.1 How to get Priority of Current Thread in Java?
• Thread class provides a method named getPriority() that is used to determine the
priority of a thread. It returns the priority of a thread through which it is called.
3.8.1.1 Let’s create a Java program in which we will determine the priority and name of
the current thread.
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.

27 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "NewThread");
System.out.println("Priority of Thread: " +t.getPriority());
System.out.println("Name of Thread: " +t.getName());
t.start();
}
}
OUTPUT

3.8.2 How to set Priority of Thread in Java?


• The setPriority() of Thread class is used to set the priority of a thread. This method
accepts an integer value as an argument and sets that value as priority of a thread
through which it is called. The syntax to set the priority of a thread is as follows:
o ThreadName.setPriority(n);
where, n is an integer value which ranges from 1 to 10.
3.8.2.1 Example Program
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "NewThread");
t.setPriority(2); // Setting the priority of thread.
System.out.println("Priority of Thread: " +t.getPriority());

28 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

System.out.println("Name of Thread: " +t.getName());


t.start();
}
}
OUTPUT

3.8.2.2 Example Program using setPriority Method in JAVA


public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t1 = new Thread(a, "First Thread");
Thread t2 = new Thread(a, "Second Thread");
Thread t3 = new Thread(a, "Third Thread");
t1.setPriority(4); // Setting the priority of first thread.
t2.setPriority(2); // Setting the priority of second thread.
t3.setPriority(8); // Setting the priority of third thread.
t1.start();
t2.start();
t3.start();
}
}
OUTPUT

29 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.9 SYNCHRONIZATION
➢ 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.
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
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. Inter-thread communication
3.9.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:
• by synchronized method
• by synchronized block
• by static synchronization
Concept of Lock in Java

➢ Synchronization is built around an internal entity known as the lock or monitor. Every
object has a 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.
3.9.1.1 By synchronized method

• If you declare any method as synchronized, it is known as synchronized method.


• Synchronized method is used to lock an object for any shared resource.

30 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

• When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

Example Program for Synchronized method


class Table
{
synchronized void printTable(int n)
{//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{

31 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500

32 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.9.1.2 By synchronized block


➢ Synchronized block can be used to perform synchronization on any specific resource
of the method.
➢ Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
➢ If you put all the codes of the method in the synchronized block, it will work same as
the synchronized method.
Points to remember for Synchronized block
o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}
3.9.1.3 Example of synchronized block
Let's see the simple example of synchronized block.
Program of synchronized block
class Table
{
void printTable(int n)
{
synchronized(this)
{//synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}//end of the method
}
class MyThread1 extends Thread
{
Table t;

33 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

3.9.1.4 Static synchronization


If you make any static method as synchronized, the lock will be on the class not on object.

34 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

Problem without static synchronization


➢ Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2.In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common
object that have a single lock. But there can be interference between t1 and t3 or t2 and
t4 because t1 acquires another lock and t3 acquires another lock.I want no interference
between t1 and t3 or t2 and t4.Static synchronization solves this problem.
Example of static synchronization

In this example we are applying synchronized keyword on the static method to perform static
synchronization.
class Table
{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{}
}
}
}

35 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

class MyThread1 extends Thread


{
public void run()
{
Table.printTable(1);
}
}
class MyThread2 extends Thread
{
public void run()
{
Table.printTable(10);
}
}
class MyThread3 extends Thread
{
public void run()
{
Table.printTable(100);
}
}
class MyThread4 extends Thread
{
public void run()
{
Table.printTable(1000);
}
}
public class TestSynchronization4
{
public static void main(String t[])
{
MyThread1 t1=new MyThread1();

36 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

MyThread2 t2=new MyThread2();


MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

Output:
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000

37 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

5000
6000
7000
8000
9000
10000

3.10 INTER THREAD COMMUNICATION


➢ Inter-thread communication or Co-operation is all about allowing synchronized threads
to communicate with each other.
➢ Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed. It is implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()
1) 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 InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.

2) 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.

38 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

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

Fig 3. 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.
7. wait(), notify() and notifyAll() methods are defined in Object class not Thread class
because they are related to lock and object has a lock.

3.10.1 Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()

39 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

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

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

3.10.2 Example of inter thread communication in java


class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();

40 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

}
}
class Test
{
public static void main (String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
3.11 JAVA THREAD SUSPEND() METHOD
➢ The suspend() method of thread class puts the thread from running to waiting state.
➢ This method is used if you want to stop the thread execution and start it again when a
certain event occurs.

41 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

➢ This method allows a thread to temporarily cease execution. The suspended thread can
be resumed using the resume() method.
➢ This method does not return any value.
3.11.1 Syntax
➢ public final void suspend()

3.11.2 Example Program


public class JavaSuspendExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaSuspendExp t1=new JavaSuspendExp ();

42 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

JavaSuspendExp t2=new JavaSuspendExp ();


JavaSuspendExp t3=new JavaSuspendExp ();
// call run() method
t1.start();
t2.start();
// suspend t2 thread
t2.suspend();
// call run() method
t3.start();
}
}
OUTPUT

3.12 JAVA THREAD RESUME() METHOD


➢ The resume() method of thread class is only used with suspend() method. This method
is used to resume a thread which was suspended using suspend() method. This method
allows the suspended thread to start again.
3.12.1 Syntax
• public final void resume()
3.12.2 Example Program
public class JavaResumeExp extends Thread
{
public void run()
{

43 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

for(int i=1; i<5; i++)


{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaResumeExp t1=new JavaResumeExp ();
JavaResumeExp t2=new JavaResumeExp ();
JavaResumeExp t3=new JavaResumeExp ();
// call run() method
t1.start();
t2.start();
t2.suspend(); // suspend t2 thread
// call run() method
t3.start();
t2.resume(); // resume t2 thread
}
}
OUTPUT

44 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.13 JAVA THREAD STOP() METHOD


➢ The stop() method of thread class terminates the thread execution. Once a thread is
stopped, it cannot be restarted by start() method.
➢ This method does not return any value.
3.13.1 Syntax
➢ public final void stop()
➢ public final void stop(Throwable obj)
• obj : The Throwable object to be thrown.
3.13.2 Example Program
public class JavaStopExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e)

45 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
// call run() method
t1.start();
t2.start();
// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}

OUTPUT

46 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.14 Multithreading. Wrappers – Auto boxing.


3.14.1 What are wrapper classes in Java?
➢ A wrapper class in Java converts a primitive data type into class object.
➢ Java is an object-oriented language that only supports pass by value. Therefore, wrapper
class objects allow us to change the original passed value. These wrapper classes help
with multithreading and synchronization because, in Java, multithreading only works
with objects.

Primitive Data Types and its corresponding Wrapper Classes

47 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.14.1.1 Wrapper class Example: Primitive to Wrapper


import java.lang.*;
public class WrapperExample1
{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

48 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

System.out.println(a+" "+i+" "+j);


}
}
OUTPUT

3.14.1.2 Wrapper class Example: Wrapper to Primitive

import java.lang.*;
public class WrapperExample2
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //unboxing i.e converting Integer to int
int j=a; //auto unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}

OUTPUT

3.14.2 AUTOBOXING

➢ Automatic conversion of primitive types to the object of their corresponding wrapper


classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.

49 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE


CS3391-OOP-UNIT-3

3.14.2.1 Java program to demonstrate Autoboxing


import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
// Autoboxing- primitive to Character object conversion
Character a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Autoboxing because ArrayList stores only objects
arrayList.add(25);
// printing the values from object
System.out.println(arrayList.get(0));
}
}
OUTPUT

50 PREPARED BY – BASTIN ROGERS C -AP/CSE- SMCE

You might also like