Unit IV - Multithreading
Unit IV - Multithreading
Unit IV
Multithreading
By
Prof. Santosh M. Sabale
Head of Computer Engg
DBATU’s Institute of Petrochemical Engineering, Lonere
After studying this chapter you will be able to
• Understand the concept of multithreading and its advantages
• Study Life cycle of thread states
• Use thread methods, assign priorities to threads
• Create and execute threads
• Write synchronized thread code
• Implement Runnable interface
Ultimately, you will be able to
Write multithreaded java programs
Introduction
• Multithreading is a Java feature that allows concurrent execution of
two or more parts of a program for maximum utilization of CPU. Each
part of such program is called a thread. So, threads are light-weight
processes within a process.
2) 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.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked): This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated: A thread is in terminated or dead state when its run() method exits.
Java Thread class
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.
Java Thread Methods
S.N Modifier and Type Method Description
.
24) static boolean holdLock() It returns true if and only if the current
thread holds the monitor lock on the
specified object.
25) static void dumpStack() It is used to print a stack trace of the current
thread to the standard error stream.
• Blocking a Thread:
A thread can also be suspended or blocked from entering into
runnable and subsequently running state by using either of the
following thread methods:
sleep () // blocked for a specified time
suspend () // blocked until further orders
wait () // block until certain condition occurs
The thread will return to the runnable state when the specified time is elapsed in
the case of sleep(), the resume () method is invoked in the case of suspend(), and
the notify () method is called in the case of wait().
Using Thread Methods: use of yield(), stop()
and sleep() methods
Program: ThreadMethods.java
Thread Priority
• In Java, each thread is assigned a priority, which affects the order in which it is
scheduled for running. The threads of the same priority are given equal
treatment by the Java scheduler and, therefore, they share the processor on a
first-come, first-serve basis.
• In Java, setPriority() method is used to set the priority of the method,
ThreadName.setPriority(intNumber);
The Thread class defines several priority constants:
MIN_PRIOPRITY = 1
NORM_PRIOPRITY = 5 //This is default setting of the thread
MAX_PRIOPRITY = 10
Most user-level processes should use NORM_PRIORITY, plus or minus 1.
Background tasks such as network I/O and screen repainting should use a value
very near to lower limit. We should be very cautious when trying to use very high
priority values. This may defeat the very purpose of using multithreads.
• By assigning priorities to threads, we can ensure that they are given
the attention (or lack of it) they deserve. For example, we may need
to answer an input as quickly as possible. Whenever multiple threads
are ready for execution, the Java system chooses the highest priority
thread and executes it. For a thread of a lower priority to gain control,
one of the following things should happen: (with the current thread):
1. It stops running at the end of run().
2. It is made to sleep using sleep().
3. It is told to wait using wait().
However, if another thread of a higher priority comes along, the
currently running thread will be preempted by the incoming thread
thus forcing the current thread to move to the runnable state. (Higher
priority thread always preempts the lower priority thread).
Program: ThreadPriority.java
Thread Scheduler
• 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.
• Difference between preemptive scheduling and time slicing:
• Under preemptive scheduling, the highest priority task executes until it enters
the waiting or dead states or a higher priority task comes into existence.
Under time slicing, a task executes for a predefined slice of time and then
reenters the pool of ready tasks. The scheduler then determines which task
should execute next, based on priority and other factors.
Thread Synchronization
• When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues. For example, if multiple
threads try to write within a same file then they may corrupt the data because
one of the threads can override data or while one thread is opening the same file
at the same time another thread might be closing the same file.
• So there is a need to synchronize the action of multiple threads and make sure
that only one thread can access the resource at a given point in time. This is
implemented using a concept called monitors. Each object in Java is associated
with a monitor, which a thread can lock or unlock. Only one thread at a time may
hold a lock on a monitor.
• Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources
within this block. Following is the general form of the synchronized statement −
• Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
• Here, the objectidentifier is a reference to an object whose lock associates with
the monitor that the synchronized statement represents. Now we are going to
see two examples, where we will print a counter using two different threads.
When threads are not synchronized, they print counter value which is not in
sequence, but when we print counter by putting inside synchronized() block, then
it prints counter very much in sequence for both the threads.
• Multithreading Example without Synchronization:
• Here is a simple example which may or may not print counter value in sequence
and every time we run it, it produces a different result based on CPU availability
to a thread.
• The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
• Types of Synchronization
Process Synchronization
Thread Synchronization
Method Description
public This method takes in no arguments. When the object of a class implementing
void run() Runnable class is used to create a thread, then the run method is invoked in
the thread which executes separately.
• The runnable interface provides a standard set of rules for the instances of
classes which wish to execute code when they are active. The most
common use case of the Runnable interface is when we want only to
override the run method. When a thread is started by the object of any
class which is implementing Runnable, then it invokes the run method in
the separately executing thread.
• A class that implements Runnable runs on a different thread without
subclassing Thread as it instantiates a Thread instance and passes itself in
as the target. This becomes important as classes should not be subclassed
unless there is an intention of modifying or enhancing the fundamental
behavior of the class.