Unit III Java
Unit III Java
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.
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 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.
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.
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.
Checked Exception
Unchecked Exception
Error
3.2.3Error
Errors are typically ignored in code because you can rarely do anything about an error.
Example :OutOfMemoryError, VirtualMachineError, AssertionError etc.
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.
Syntax of try-catch
try
{
//code that may throw exception
}
catch(Exception_class_Name ref){ }
If we have to perform different tasks at the occurrence of different Exceptions, we can use
multiple catch blocks.
TestMultipleCatchBlock.java
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
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
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");
}
}
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.
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:
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:
Example:Test.java
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
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;
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
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.
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");
}
}
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
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 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;
else
{
System.out.println("Eligible to Vote..");
}
}
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.1 Multithreading
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.
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.
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.
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.
Memory sharing Completely isolated and do not Shares memory with each other.
share memory.
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
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 :
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 :
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
ended after execution of run( ) method. A Thread is moved into dead state if it returns the run( )
method.
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)
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
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 .
void start( );
Example:SingleThread.java
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
Step 2 : As a second step, we will instantiate a Thread object using the following constructor
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");
}
}
Output:
Welcome Method
Main method executed by main thread
Run method executed by child Thread
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)
catch(Exception e){System.out.println(e);}
}
}
}
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();
}
}
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
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);}
}
}
}
}
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
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
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.
}
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
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:
Example: Customer.Java
class Customer
{
int amount=10000;
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();
}
}
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
}
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.
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.
Example:
public class DeadLockSample
{
String R1 = "R1";
String R2 = "R2";
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();
}
}
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.
ThreadGroup(ThreadGroup creates a thread group with given parent group and name.
parent, String name)
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.
String getName() This method returns the name of the 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.
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 setMaxPriority(int pri) This method sets the maximum priority of the
group.
Example: ThreadGroupDemo.java
Output:
one
two
three
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
Explanation:
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.
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.
Checked Exception
Unchecked Exception
Error
3.What are the Java Exception Keywords (or) How exception handling is handled in java.
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.
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;
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
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