0% found this document useful (0 votes)
2 views

Unit III Java

Uploaded by

Prabhu B
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 views

Unit III Java

Uploaded by

Prabhu B
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/ 42

IT T45- Java Programming

Unit: III
Concepts of Exception handling, types of exceptions, usage of try, catch, throw, throws and finally
keywords, Built-in exceptions, creating own exception sub classes, Concepts of Multithreading,
differences between process and thread, thread life cycle ,creating multiple threads using Thread class,
Runnable interface, Synchronization, thread priorities, inter thread communication, daemon threads,
deadlocks, thread groups.

3.1 Concepts of Exception Handling:

Exception:
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Java Exception

A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for
doing something about the exception is called an exception handler.

Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Advantage of exception handling

Exception handling ensures that the flow of the program doesn‟t break when an exception
occurs. For example, if a program has bunch of statements and an exception occurs mid-way after
executing certain statements then the statements after the exception will not execute and the program
will terminate abruptly.

Difference between error and exception

Error- Errors indicate that something severe enough has gone wrong, the application should crash
rather than try to handle the error.

Exceptions -Exceptions are events that occur in the code. A programmer can handle such conditions
and take necessary corrective actions.

SMVEC-Department of Information Technology Page 1


IT T45- Java Programming

Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception 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.

Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java
programs. Errors are generated to indicate errors generated by the runtime environment. Example:
JVM is out of memory. Normally, programs cannot recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException Class.Java
defines several exception classes inside the standard package java.lang.

Fig 3.1 Exception Hierarchy

3.2 Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as
the unchecked exception. According to Oracle, there are three types of exceptions:

 Checked Exception
 Unchecked Exception
 Error

3.2.1 Checked Exception


The exception that can be predicted by the programmer at the compile time.
Example : File that need to be opened is not found. These type of exceptions must be checked
at compile time.

3.2.2 Unchecked Exception


Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are
ignored at compile time.
Example : ArithmeticException, NullPointerException, Array Index out of Bound exception.
Unchecked exceptions are checked at runtime.

3.2.3Error
Errors are typically ignored in code because you can rarely do anything about an error.
Example :OutOfMemoryError, VirtualMachineError, AssertionError etc.

SMVEC-Department of Information Technology Page 2


IT T45- Java Programming

3.3 Usage of try, catch, throw, throws and finally keywords

3.3.1 Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try
block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with
method signature.

3.3.2 try-catch 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 of try-catch

try
{
//code that may throw exception
}
catch(Exception_class_Name ref){ }

Syntax of try-finally block


try
{
//code that may throw exception
}
finally{ }

3.3.3 catch block


Java catch block is used to handle the Exception. It must be used after the try block .We can use
multiple catch block with a single try.

SMVEC-Department of Information Technology Page 3


IT T45- Java Programming

Example Program without exception handling


Testtrycatch1.java

public class Testtrycatch1


{
public static void main(String args[])
{
int data=50/0;//may throw exception
System.out.println("Division Result");
}
}

Example Program with exception handling


Testtrycatch1.java

public class Testtrycatch2


{
public static void main(String args[]) Output:
{ Exception in thread main
try java.lang.ArithmeticException:/ by zero
{
Can‟t able to divide by Zero
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Can‟t able to divide by Zero”)
}
}

3.3.4 Multiple catch block

If we have to perform different tasks at the occurrence of different Exceptions, we can use
multiple catch blocks.

TestMultipleCatchBlock.java

public class TestMultipleCatchBlock


{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception Occured");
SMVEC-Department of Information Technology Page 4
IT T45- Java Programming

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Exception Occured");
}
catch(Exception e)
{
System.out.println("common task completed");
}
System.out.println("Exception Handled”);
}
}

Output
Arithmetic Exception Occurred
Exception Handled

3.3.5 Nested try block


The try block within a try block is known as nested try block in java.

Use of 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.

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{

SMVEC-Department of Information Technology Page 5


IT T45- Java Programming

Example:Nested.java
classNested
{
public static void main(String args[])
{
try
{
try
{
System.out.println("Division Operation");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Other Exceptions”);
}
catch(Exception e)
{
System.out.println("Exception Handled");
}
System.out.println("Normal Execution");
}
}

3.3.6 throw keyword


The Java throw keyword is used to explicitly throw an exception. We can throw either checked
or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom
exception.

Syntax:
throw exception;
Example:
throw new IOException("sorry device error);

But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For
example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception
class.

SMVEC-Department of Information Technology Page 6


IT T45- Java Programming

Example: TryCatchDemo2.java
importjava.util.*;
public class TryCatchDemo2
{
public static void main( String args [ ] )
{
int age;
Scanner in = new Scanner( System.in );
try
{
System.out.print( "Enter your age: " );
age = in.nextInt( );
if ( age < 0 )
throw new RuntimeException( );
System.out.println( age + " years" );
}
catch ( RuntimeException e )
{
System.out.println( "Age cannot be negative" );
}
catch ( InputMismatchException e )
{
System.out.println( "Bad integer" );
}
System.out.println( "Completed" );
}
}

Output:

Exception in thread main java.lang.ArithmeticException:not valid

3.3.7 throws keyword


throws is a keyword in Java which is used in the signature of 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.

Syntax:
typemethod_name(parameters) throws exception_list

exception_list-is a comma separated list of all the exceptions which a method might throw.

In a program, if there is a chance of rising an exception then compiler always warn us about it
and compulsorily we should handle that checked exception. To prevent this compile time error we can
handle the exception in two ways:

 By using try catch


 By using throws keyword

SMVEC-Department of Information Technology Page 7


IT T45- Java Programming

Example:Test.java
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{ Output:
try Inside check function
{ caught java.lang.ArithmeticException: demo
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

Difference between throw and throws


throw throws

The throw keyword is used to throw an exception The throws keyword is used to declare an exception
explicitly. possible during its execution.

The throw keyword is followed by an instance of The throws keyword is followed by one or more
Throwable class or one of its sub-classes. Exception class names separated by commas.

The throw keyword is declared inside a method The throws keyword is used with method signature
body. (method declaration).

We cannot throw multiple exceptions using throw We can declare multiple exceptions (separated by
keyword. commas) using throws keyword.

Example: Example:
throw new IOException("Input Exception) throws IOException,ArrayIndexBoundException;

3.3.8 finally clause

A finally keyword is used to create a block of code that follows a try block. A finally block of
code is always executed whether an exception has occurred or not. Using a finally block, it lets you

SMVEC-Department of Information Technology Page 8


IT T45- Java Programming

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 catch block.

Fig 3.2 Finally block execution


Difference between final,finally and finalize
final finally finalize
Final is used to apply restrictions Finally is used to place Finalize is used to perform
on class, method and variable. important code, it will be clean up processing just before
executed whether exception is object is garbage collected.
Final class can't be inherited, final handled or not.
method can't be overridden and
final variable value can't be
changed.
Final is a keyword. Finally is a block. Finalize is a method.

Syntax of Finally block


try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}

SMVEC-Department of Information Technology Page 9


IT T45- Java Programming

The below program will catch the exception when the number is divided by zero. The finally code is
always executed whether an exception has occurred or not. That is it will be executed at the end of the
program execution irrespective of the exception.

Example:FinallyExample.java
classFinallyExample
{
public static void main(String args[]) Output:
{ Number should not be divided by zero
try This is finally block
{ Out of try-catch-finally
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e)
{
System.out.println("Number should not be divided by zero");
}
// Finally block will always execute even if there is no exception in try block

finally
{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}

3.4 Built-in Exceptions


Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own 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.

Fig 3.3 Types of Exceptions

Types of Exception Description

Arithmetic Exception It is thrown when an exceptional condition has occurred in an


arithmetic operation.

SMVEC-Department of Information Technology Page 10


IT T45- Java Programming

ArrayIndexOutOfBoundException 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 than the size of the string

Examples of Built-in Exception:


ArithmeticException_Demo.java

classArithmeticException_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
NullPointer Exception
SMVEC-Department of Information Technology Page 11
IT T45- Java Programming

The above program handles the divide the number by Zero exception, when a number is divided by
zero

NullPointer_Demo.java
classNullPointer_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..");
}
}
}

Output:
NullPointerException.

StringIndexOutOfBound_Demo.java

classStringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{
String a = "Java Programming"; // length is 16
char c = a.charAt(18); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("StringIndexOutOfBoundsException");
}
}
}

Output:
StringIndexOutOfBoundsException

SMVEC-Department of Information Technology Page 12


IT T45- Java Programming

3.5 Creating Own Exception sub classes


3.5.1 User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to handle the certain situation. In such
cases, user can also create exceptions which are called „user-defined Exceptions‟. User Defined
Exception or custom exception is creating our own exception class and throws that exception using
„throw‟ keyword. This can be done by extending the class Exception.

Following steps are followed for the creation of user-defined Exception.

Step 1: The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a subclass of it. This is
done as:
classMyException extends Exception

Step 2: We can write a default constructor in his own exception class.


MyException(){ }

We can also create a parameterized constructor with a string as a parameter.


We can use this to store exception details. We can call super class(Exception) constructor from this and
send the string there.
MyException(String str)
{
super(str);
}

Step 3: To raise exception of user-defined type, we need to create an object to his exception class and
throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;

Example:MyException.java
import java.io.*;
import java.util.Scanner;

class InvalidAgeException extends Exception


{
InvalidAgeException (String s)
{
super(s);
}
}
class TestException
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
{
throw new InvalidAgeException("Not Eligible to vote !!!");
}
SMVEC-Department of Information Technology Page 13
IT T45- Java Programming

else
{
System.out.println("Eligible to Vote..");
}
}

public static void main(String args[])


{
int a;
Scanner s=new Scanner(System.in);
System.out.print("\nEnter Your Age : ");
a=s.nextInt();
try
{
validate(a);
}
catch(Exception m)
{
System.out.println("Exception Occured : "+m);
}
}
}

Output:
Enter your age: 16
Exception Occured : Not Eligible to vote !!!

Details of account numbers, customer names, and balance amounts are taken in the form of
three arrays. In main( ) method, the details are displayed using a for-loop. if in any account the balance
amount is less than the minimum balance amount to be kept in the account, then MyException is raised
and a message is displayed “Balance amount is less”.

3.6 Concepts of Multithreading

3.6.1 Multithreading

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


Thread:
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process. Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


 It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

SMVEC-Department of Information Technology Page 14


IT T45- Java Programming

 You can perform many operations together, so it saves time.


 Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Thread in java
A thread is a lightweight sub process, the smallest unit of processing. It is a separate path of
execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
A thread is executed inside the process. There is context-switching between the threads. There
can be multiple processes inside the OS, and one process can have multiple threads.

Fig 3.4 Thread


3.6.2 Difference between Process and Thread:
 The process is an execution of a program
 Thread is an execution of a program driven by the environment of a process.
 Thread is that processes are isolated with each other whereas threads share memory or resources
with each other.

Definition of Process
The process is the execution of a program and performs the relevant actions specified in a
program, or it is an execution unit where a program runs. The operating system creates schedules and
terminates the processes for the use of the CPU. The other processes created by the main process are
known as child process.

Properties of a Process:
 Creation of each process includes system calls for each process separately.
 A process is an isolated execution entity and does not share data and information.
 Processes use IPC (Inter-process communication) mechanism for communication which
significantly increases the number of system calls.
 Process management consumes more system calls.
 Each process has its own stack and heap memory, instruction, data and memory map.

SMVEC-Department of Information Technology Page 15


IT T45- Java Programming

Definition of Thread
The thread is a program execution that uses process resources for accomplishing the task. All
threads within a single program are logically contained within a process. The kernel allocates a stack
and a thread control block (TCB) to each thread. The operating system saves only the stack pointer and
CPU state at the time of switching between the threads of the same process. Threads are implemented
in three different ways; these are kernel-level threads, user-level threads, hybrid threads.

Properties of a Thread:
 Only one system call can create more than one thread (Lightweight process).
 Threads share data and information.
 Threads shares instruction, global and heap regions but has its own individual stack and registers.
 Thread management consumes no or fewer system calls as the communication between threads can
be achieved using shared memory.
 The isolation property of the process increases its overhead in terms of resource consumption.

Comparison Process Thread

Basic Program in execution. Lightweight process or part of it.

Memory sharing Completely isolated and do not Shares memory with each other.
share memory.

Resource consumption More Less

Efficiency Less efficient as compared to the Enhances efficiency in the context


process in the context of of communication.
communication.

Time required for creation More Less

Context switching time Takes more time. Consumes less time.

Uncertain termination Results in loss of process. A thread can be reclaimed.

Time required for More Less


termination

3.7 Life Cycle of a Thread


A thread goes through various stages in its life cycle. 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

SMVEC-Department of Information Technology Page 16


IT T45- Java Programming

Fig 3.5 Life Cycle of Thread


New State : A Thread is called in new state when it is created. To create a new thread you may create
an instance of Thread class or you can create a subclass of Thread and then you can create an instance
of your class.
Example :

Thread thread = new Thread();

Newly created thread is not in the running state. To move the thread in running state the start( )
method is used.
Runnable State: A Thread is called in runnable state when it is ready to run and its waiting to give
control. A thread in this state is considered to be executing its task. To move control to another thread
we can use yield( ) method.
Example :

Thread thread = new Thread();


thread.yield( );

Running State: A Thread is called in running state when it is in its execution mode. In this state
control of CPU is given to the Thread. To execute a Thread the scheduler selects the specified thread
from runnable pool.
Blocked State : A Thread is called in blocked state when it is not allowed to enter in runnable and/or
running state. A thread is in blocked state when it is suspend, sleep or waiting.
Example :

Thread thread = new Thread();


thread.sleep( );

Dead State: A Thread is called in dead state when its run() method execution is completed. It enters
the terminated state when it completes its task or otherwise terminates. The life cycle of Thread is

SMVEC-Department of Information Technology Page 17


IT T45- Java Programming

ended after execution of run( ) method. A Thread is moved into dead state if it returns the run( )
method.

Methods used in Life cycle of Thread

public void yield( ) It causes the currently executing thread object to temporarily pause
and allow other threads to execute.
public void suspend( ) It is used to suspend the thread (deprecated).
public void resume( ) It is used to resume the suspended thread (deprecated)
public void stop( ) It is used to stop the thread (deprecated).

Example: ChildThread.java
class ChildThread implements Runnable
{
Thread t;

ChildThread( )
{
t = new Thread(this);
System.out.println("Thread is in new state");
t.start();
}
public void run()
{
System.out.println("Thread is in runnable state");
Scanner s = new Scanner(System.in);
System.out.println("Thread entering blocked state");
System.out.print("Enter a string: ");
String str = s.next( );
for(int i = 1; i <= 3; i++)
{
try
{
System.out.println("Thread suspended");
t.sleep(1000);
System.out.println("Thread is running");
}
catch(InterruptedException e)
{
System.out.println("Thread interrupted");
}
System.out.println("Thread terminated");
t.stop( );
}
}
SMVEC-Department of Information Technology Page 18
IT T45- Java Programming

}
classMainPgm
{
public static void main(String[] args)
{
newChildThread();
}
}
Output :
Thread is in new state
Thread is in runnable state
Thread entering blocked state
Enter a string: hai
Thread suspended
Thread is running
Thread terminated
3.8 Creating multiple threads using Thread class
There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.

Java provides Thread class to achieve thread programming. Thread class provides constructors
and methods to create and perform operations on a thread. Thread class extends Object class and
implements Runnable interface.

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:

Method Description
public void run() Is used to perform action for a thread.
public void start() Starts the execution of the thread.JVM calls the run()
method on the thread.
public void sleep(long miliseconds) Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void join() Waits for a thread to die.
public void join(long miliseconds) Waits for a thread to die for the specified miliseconds.
public Thread currentThread() Returns the reference of currently executing thread.
public intgetId() Returns the id of the thread.
public Thread.StategetState() Returns the state of the thread.
SMVEC-Department of Information Technology Page 19
IT T45- Java Programming

public booleanisAlive() Tests if the thread is alive.


public void interrupt() Interrupts the thread.
publicbooleanisInterrupted() Tests if the thread has been interrupted.
public static boolean interrupted() Tests if the current thread has been interrupted.

3.8.1 Steps to be followed to create a Thread by Extending a Thread Class:


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: We have to override the run( ) method available in Thread class. This method provides an entry
point for the thread and you will put our 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( );

Example:SingleThread.java

classSingleThread extends Thread


{
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
Test t = new Test( );
t.start( );
System.out.println("Main method executed by main thread");
}
}
Output:
Main method executed by main thread
Run method executed by child Thread

3.8.2 Create a Thread by implementing a Runnable interface:


The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread.

Step 1: As a first step, we 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( ) { }

SMVEC-Department of Information Technology Page 20


IT T45- Java Programming

Step 2 : As a second step, we will instantiate a Thread object using the following constructor

Thread(Runnable threadObj, String threadName);

threadObj- is an instance of a class that implements the Runnable interface


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

void start();

The below example implements the Runnable interface in order to create the Thread in java

Example: ThreadTest.java
class Information
{
public static void m1()
{
System.out.println("Welcome Method");
}
}

classThreadTest extends Geeks implements Runnable


{
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
Test t = new Test();
t.m1();
Thread t1 = new Thread(t);
t1.start();
System.out.println("Main method executed by main thread");
}
}

Output:

Welcome Method
Main method executed by main thread
Run method executed by child Thread

SMVEC-Department of Information Technology Page 21


IT T45- Java Programming

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

Need of Synchronization:
The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization

Thread Synchronization:
There are two types of thread synchronization
 Mutual exclusive
 Synchronized method.
 Synchronized block.
 static synchronization.
 Cooperation(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.

Understanding the problem without Synchronization In this example, there is no synchronization,


so output is inconsistent.
class Table
{
void printTable(int n) //method not synchronized
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
SMVEC-Department of Information Technology Page 22
IT T45- Java Programming

catch(Exception e){System.out.println(e);}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t) Output:
{ 5
this.t=t; 100
} 10
public void run() 200
{ 15
t.printTable(5); 300
} 20
} 400
class MyThread2 extends Thread 25
{ 500
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

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

3.9.1.1 Java synchronized method


If we declare any method as synchronized, it is known as synchronized method. Synchronized
method is used to lock an object for any shared resource. 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: Table.java
SMVEC-Department of Information Technology Page 23
IT T45- Java Programming

class Table
{
synchronized void printTable(int n) //method synchronized
{
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;
} Output:
public void run() 5
{ 10
t.printTable(5); 15
} 20
25
} 100
class MyThread2 extends Thread 200
{ 300
Table t; 400
MyThread2(Table t) 500
{ 500
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class TestSynchronization1
{
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( );
} }
SMVEC-Department of Information Technology Page 24
IT T45- Java Programming

3.9.1.2 Synchronized block in java


Synchronized block can be used to perform synchronization on any specific resource of the
method. Suppose we have 50 lines of code in your method, but we want to synchronize only 5 lines,
you can use synchronized block. If we put all the codes of the method in the synchronized block, it will
work same as the synchronized method.

 Synchronized block is used to lock an object for any shared resource.


 Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression)
{
//code block
}

Table.java
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);}
}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}

SMVEC-Department of Information Technology Page 25


IT T45- Java Programming

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
Output:
{
5
this.t=t;
10
}
15
public void run()
20
{
25
t.printTable(100);
100
}
200
}
300
400
class TestSynchronization1
500
{
500
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();
}
}

3.9.1.3 Synchronized block by using anonymous class:


class Table
{
voidprintTable(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);}
}
}
}
}
public class TestSynchronizedBlock2
{
public static void main(String args[])
{
final Table obj = new Table(); //only one object

SMVEC-Department of Information Technology Page 26


IT T45- Java Programming

Thread t1=new Thread()


{
public void run()
{
obj.printTable(5);
}
}; Output:
Thread t2=new Thread() 5
{ 10
public void run() 15
{ 20
obj.printTable(100); 25
} 100
}; 200
300
t1.start(); 400
t2.start(); 500
} 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.

Fig 3.6 static synchronization

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. So there must not be any interference between t1 and t3 or t2 and t4.Static
synchronization solves this problem.

Example of static synchronization


class Table
{
synchronized static void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
SMVEC-Department of Information Technology Page 27
IT T45- Java Programming

try
{
Thread.sleep(400);
}
catch(Exception e){}
}
}
}
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();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
SMVEC-Department of Information Technology Page 28
IT T45- Java Programming

Thread Scheduler in Java


 Thread scheduler in java is the part of the JVM that decides which thread should run.
 There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
 Only one thread at a time can run in a single process.
 The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

The join( ) method- The join( ) method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.

Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException

class TestJoinMethod1 extends Thread


{
public void run( )
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(500);
}
catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try
{
t1.join( );
}
catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}

Naming Thread
The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using
setName( ) method.

SMVEC-Department of Information Technology Page 29


IT T45- Java Programming

3.9 Priority of a Thread (Thread Priority):


Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread scheduler 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.
Three constants that are defined in Thread class:
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY).


The value of MIN_PRIORITY is 1
The value of MAX_PRIORITY is 10.

3.9.1 Methods in Thread Priority

public intgetPriority() Returns the priority of the thread.


publicintsetPriority(int priority) Changes the priority of the thread.
public String getName() Returns the name of the thread.
public void setName(String name) Changes the name of the thread.

Example of priority of a Thread:


class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}

Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

SMVEC-Department of Information Technology Page 30


IT T45- Java Programming

3.10 Inter-thread communication in Java:


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a
thread is paused running in its critical section and another thread is allowed to enter (or lock) in the
same critical section to be executed. It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()

wait( ) method: This 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 time.
InterruptedException

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 random and occurs at the
choice of the implementation.
Syntax:
public final void notify()

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

public final void notifyAll()

Fig 3.7 Inter thread communication in java

SMVEC-Department of Information Technology Page 31


IT T45- Java Programming

3.10.1 Steps followed in Inter thread Communication:


 Threads enter to acquire lock.
 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait( ) method on the object. Otherwise it releases
the lock and exits.
 If you call notify( ) or notifyAll( ) method, thread moves to the notified state (runnable state).
 Now thread is available to acquire lock.
 After completion of the task, thread releases the lock and exits the monitor state of the object.

Difference between wait( ) and sleep( )


wait( ) sleep( )
wait() method releases the lock sleep() method doesn't release the lock.
It is the method of Object class It is the method of Thread class
It is the non-static method It is the static method
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
methods completed.

Example: Customer.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();
}
}

SMVEC-Department of Information Technology Page 32


IT T45- Java Programming

class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start( );
Output: going to withdraw...
Less balance; waiting for deposit...
new Thread()
going to deposit...
{
deposit completed...
public void run()
withdraw completed
{
c.deposit(10000);
}
}.start();

}
}

3.11 Daemon Thread in Java


Daemon thread in java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
 There are many java daemon threads running automatically e.g. gc, finalizer etc.
 We can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.

Characteristics of Daemon Thread in Java


 It provides services to user threads for background supporting tasks. It has no role in life than to
serve user threads.
 Its life depends on user threads.
 It is a low priority thread.

Need of terminating daemon thread if there is no user thread by JVM:


The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM
terminates the daemon thread if there is no user thread.

3.11.1 Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.
public booleanisDaemon(): Tests if the thread is a daemon thread.
public void setDaemon(boolean b): Marks the thread as daemon or user
thread.

SMVEC-Department of Information Technology Page 33


IT T45- Java Programming

Example: MyThread.java
public class TestDaemonThread1 extends Thread
{
public void run( )
{
if(Thread.currentThread().isDaemon())//checking for daemon thread
{
System.out.println("Daemon Thread Work");
}
else
{
System.out.println("User Thread Work");
}
}
public static void main(String[] args)
{
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads Output
t2.start(); Daemon thread work
t3.start(); User thread work
} User thread work
}

3.11.2 Java Thread Pool

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many
times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is
pulled out and assigned a job by the service provider. After completion of the job, thread is contained in
the thread pool again.

3.12 Deadlock in java

The synchronized keyword is used to make the class or method thread-safe which means only
one thread can have lock of synchronized method and use it, other threads have to wait till the lock
releases and anyone of them acquire that lock.It is important to use if our program is running in multi-
threaded environment where two or more threads execute simultaneously. But sometimes it also causes
a problem which is called Deadlock

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an object
lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock,
the condition is called deadlock.

SMVEC-Department of Information Technology Page 34


IT T45- Java Programming

Fig 3.8 Deadlock

Example:
public class DeadLockSample
{
String R1 = "R1";
String R2 = "R2";

Thread T1 = new Thread(new Runnable()


{
public void run()
{
System.out.println("Starting T1");
// Acquired R1
synchronized (R1)
{
try
{
Thread.sleep(100);
}
catch (Exception ex) { }
synchronized (R2)
{
System.out.println("Acquired both!");
}
}
// If we reach here, no deadlock!
System.out.println("Completed T1");
}
});
Thread T2 = new Thread(new Runnable()
{
public void run()
{
System.out.println("Starting T2");

SMVEC-Department of Information Technology Page 35


IT T45- Java Programming

synchronized (R2)
{
try
{
Thread.sleep(100);
}
catch (Exception e{ }
synchronized (R1)
{
System.out.println("Acquired both!");
}
}
// If we reach here, no deadlock!
System.out.println("Completed T2");
}
});
public static void main(String[] args)
{
DeadLockSample ds = new DeadLockSample();
ds.T1.start();
ds.T2.start();
}
}

3.13 ThreadGroup in Java

Java provides a convenient way to group multiple threads in a single object. In such way, we
can suspend, resume or interrupt group of threads by a single method call.
Note: Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
 A ThreadGroup represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread
group has a parent.
 A thread is allowed to access information about its own thread group, but it cannot access the
information about its thread group's parent thread group or any other thread groups.

3.13.1 Constructors of ThreadGroup class

There are only two constructors of ThreadGroup class

ThreadGroup(String name) creates a thread group with given name.

SMVEC-Department of Information Technology Page 36


IT T45- Java Programming

ThreadGroup(ThreadGroup creates a thread group with given parent group and name.
parent, String name)

3.13.2 Methods of ThreadGroup class

There are many methods in ThreadGroup class.

Modifier and Method Description


Type

void checkAccess() This method determines if the currently running


thread has permission to modify the thread group.

int activeCount() This method returns an estimate of the number of


active threads in the thread group and its
subgroups.

int activeGroupCount() This method returns an estimate of the number of


active groups in the thread group and its
subgroups.

void destroy() This method destroys the thread group and all of
its subgroups.

int enumerate(Thread[] list) This method copies into the specified array every
active thread in the thread group and its
subgroups.

int getMaxPriority() This method returns the maximum priority of the


thread group.

String getName() This method returns the name of the thread group.

ThreadGroup getParent() This method returns the parent of the thread


group.

void interrupt() This method interrupts all threads in the thread


group.

boolean isDaemon() This method tests if the thread group is a daemon


thread group.

void setDaemon(boolean daemon) This method changes the daemon status of the
thread group.

boolean isDestroyed() This method tests if this thread group has been
destroyed.

SMVEC-Department of Information Technology Page 37


IT T45- Java Programming

void list() This method prints information about the thread


group to the standard output.

boolean parentOf(ThreadGroup g) This method tests if the thread group is either the
thread group argument or one of its ancestor
thread groups.

void suspend() This method is used to suspend all threads in the


thread group.

void resume() This method is used to resume all threads in the


thread group which was suspended using
suspend() method.

void setMaxPriority(int pri) This method sets the maximum priority of the
group.

void stop() This method is used to stop all threads in the


thread group.

String toString() This method returns a string representation of the


Thread group.

Example: ThreadGroupDemo.java

public class ThreadGroupDemo implements Runnable


{
public void run( )
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg1, runnable,"one");


t1.start();
Thread t2 = new Thread(tg1, runnable,"two");
t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();

System.out.println("Thread Group Name: "+tg1.getName());


tg1.list();
}
SMVEC-Department of Information Technology Page 38
IT T45- Java Programming

Output:
one

two

three

Thread Group Name: Parent ThreadGroup

java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]

Thread[one,5,Parent ThreadGroup]

Thread[two,5,Parent ThreadGroup]

Thread[three,5,Parent ThreadGroup]

Explanation:

ThreadGroup tg1 = new ThreadGroup("Group A");

Thread t1 = new Thread(tg1,new MyRunnable(),"one");

Thread t2 = new Thread(tg1,new MyRunnable(),"two");

Thread t3 = new Thread(tg1,new MyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class
that implements Runnable interface and "one", "two" and "three" are the thread names.

SMVEC-Department of Information Technology Page 39


IT T45- Java Programming

Two Marks
1. What is meant by Exception?
An Exception is a condition that is caused by a runtime error in the program. An error may
produce an incorrect output or may terminate the execution of the program.

2. What are the different Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as
the unchecked exception. According to Oracle, there are three types of exceptions:

 Checked Exception
 Unchecked Exception
 Error

3.What are the Java Exception Keywords (or) How exception handling is handled in java.

There are 5 keywords which are used in handling exceptions in Java.


Keyword Description

try The "try" keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try
block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with
method signature.

3. Difference between throw and throws


throw throws
The throw keyword is used to throw an exception The throws keyword is used to declare an exception
explicitly. possible during its execution.
The throw keyword is followed by an instance of The throws keyword is followed by one or more
Throwable class or one of its sub-classes. Exception class names separated by commas.

The throw keyword is declared inside a method The throws keyword is used with method signature
body. (method declaration).
We cannot throw multiple exceptions using throw We can declare multiple exceptions (separated by
keyword. commas) using throws keyword.

Example: Example:
throw new IOException("Input Exception) throws IOException,ArrayIndexBoundException;

SMVEC-Department of Information Technology Page 40


IT T45- Java Programming

4. What is thread? How it differ from other process?


Both processes and threads are independent sequences of execution. The typical difference
is that threads (of the same process) run in a shared memory space, while processes run in separate
memory spaces.
5. What are the two methods by which we stop the threads?
We can stop the thread by calling the stop( ) method.
The stop ( ) method is used when premature death of the thread is required. The thread gets stopped
automatically at the end of the program.

6. Define Multithreading?
Multitasking means executing several programs at a time, in system terminology, it is called
multithreading. Thread is single line of execution within the program.
7. What are the two ways of creating java threads?
Method 1: By creating a thread class: Define a class that extends Thread class and override its
run( ) method with the code required by the thread.
Method 2: By converting a class to a thread: Define a class that implements Runnable interface.
The Runnable interface has only one method run( ), that is to be defined in the method with the
code to be executed by the thread.
8. What is life cycle of thread?
 New born state
 Runnable state
 Running state
 Blocked state
 Dead state
9. Explain how can we implement a runnable interface?
If we want multithreading support in a class that already extends a class other than Thread, we
must implement the Runnable interface in that class. Class Thread itself implements the Runnable
interface (package java.lang).
public class Thread extends Object implements Runnable

10. Write the methods of threads?


 void start( )-This method will start new thread of execution by calling run() method of
Thread/runnable object.
 void run( ) - This method is entry point of thread. Execution of thread starts from this
method.
 void sleep(int sleeptime) - This method suspend thread for mentioned time duration in
argument (sleeptime in ms)
 void yield( ) - invoking this method the current thread pause its execution temporarily and
allow other threads to execute.

11. Define 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.

SMVEC-Department of Information Technology Page 41


IT T45- Java Programming

Need of Synchronization:
The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.
12. Define Mutual Exclusion.
Each thread accessing a shared object stops all other threads from sharing the data
simultaneously; this is called as mutual exclusion.
13. Define Monitors.
Monitors and monitor locks can thus be used to enforce mutual exclusion. If an operation
requires the executing thread to hold a lock while the operation is performed, a thread must acquire
the lock before proceeding with the operation. Other threads attempting to perform an operation that
requires the same lock will be blocked until the first thread releases the lock,

14. Write short notes about the Priority of a Thread (Thread Priority):
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread scheduler 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.
Three constants that are defined in Thread class:
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY).


The value of MIN_PRIORITY is 1
The value of MAX_PRIORITY is 10.

15. What are daemon threads?


A daemon thread is a thread that runs for the benefit of other threads. Daemon threads do not
prevent a program from terminating. The garbage collector is a daemon thread.

16. Define 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:
 wait()
 notify()
 notifyAll()

17. What is called as Deadlock in java


Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an object
lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock,
the condition is called deadlock.

SMVEC-Department of Information Technology Page 42

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy