0% found this document useful (0 votes)
65 views51 pages

Multi Thearding

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)
65 views51 pages

Multi Thearding

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/ 51

MultiThreading

Introduction
⚫ A multithreaded program contains two or more
parts that can run concurrently. Each part of such
a program is called a thread, and each thread
defines a separate path of execution. Thus,
multithreading is a specialized form of
multitasking.
⚫ In a thread-based multitasking environment, the
thread is the smallest unit of dispatchable code.
This means that a single program can perform
two or more tasks simultaneously. For instance,
a text editor can format text at the same time that
it is printing, as long as these two actions are being
performed by two separate threads.
Introduction
⚫ Threads, on the other hand, are lightweight.
They share the same address space and
cooperatively share the same heavyweight
process. Inter thread communication is
inexpensive, and context switching from one
thread to the next is low cost.
⚫ Multithreading enables you to write very efficient
programs that make maximum use of the
CPU, because idle time can be kept to a
minimum.
Java Thread Model
⚫ A thread exists in several states. A thread can be in
the following states:
◦ New born thread (Newly created thread)
◦ Runnable (It is waiting in a queue for CPU
time)
◦ Running (Under execution)
◦ Blocked (Waiting for resources)
◦ Dead (Halts the execution immediately and
never resumes)
Java Thread Model
Java Thread Model
⚫ Java thread model can be defined in the following
three sections:
◦ Thread Priorities
◦ Synchronization
◦ Messaging
⚫ Thread Priorities:
◦ Each thread has its own priority in Java. Thread
priority is an absolute integer value. Thread
priority decides only when a thread switches
from one running thread to next, called context
switching. Priority does increase the running
time of the thread or gives faster execution.
Java Thread Model
⚫ Synchronization:
◦ Because multithreading introduces an asynchronous
behaviour to your programs, there must be a way
for you to enforce synchronicity when you need it.
For example, if you want two threads to
communicate and share a complicated data
structure, such as a linked list, you need some way
to ensure that they don’t conflict with each other.
◦ That is, you must prevent one thread from writing
data while another thread is in the middle of reading
it. For this purpose, Java implements elegant twists
on an age-old model of Inter Process
Synchronization: the Monitor.

Java Thread Model
◦ The monitor is a control mechanism first
defined by C.A.R. Hoare. You can think of a
monitor as a very small box that can hold
only one thread. Once a thread enters a
monitor, all other threads must wait until
that thread exits the monitor. In this way, a
monitor can be used to protect a shared asset
from being manipulated by more than one
thread at a time.
Java Thread Model
⚫ Messaging:
◦ After you divide your program into separate
threads, you need to define how they will
communicate with each other. By contrast, Java
provides a clean, low-cost way for two or more
threads to talk to each other, via calls to
predefined methods that all objects have.
◦ Java’s messaging system allows a thread to enter
a synchronized method on an object, and then
wait there until some other thread explicitly
notifies it to come out.
Thread class and its methods
⚫ The java.lang.Thread class is a thread of
execution in a program. Java’s multithreading
system is built upon the Thread class, its methods.
To create a new thread, your program has to
extend Thread class. The Thread class defines
several methods that help manage threads.
Thread class and its methods
Thread class and its methods
⚫ When a Java program starts up, one thread begins
running immediately. This is usually called the
main thread of your program, because it is the
one that is executed when your program begins.
⚫ The main thread is important for two reasons:
• It is the thread from which other “child”
threads will be generated.
• Often, it must be the last thread to finish
execution because it performs various shutdown
actions.
Thread class and its methods
⚫ Although the main thread is created automatically
when your program is started, it can be controlled
through a Thread object. To do so, you must obtain
a reference to it by calling the method
currentThread( ), which is a public static
member of Thread.
⚫ Its general form is shown here:
static Thread currentThread( )
⚫ You can set the name of a thread by using
setName( ).You can obtain the name of a thread
by calling getName( ). These methods are
members of the Thread class and are declared like
this:
Thread class and its methods
final void setName(String threadName)
final String getName( )
Here, threadName specifies the name of the thread.
⚫ The sleep( ) method causes the thread from which it
is called to suspend execution for the specified
period of milliseconds. Its general form is shown
here:
static void sleep(long milliseconds) throws
InterruptedException
⚫ The parameter for sleep() method is specified in
milliseconds (1000 milliseconds = 1 second). This
method may throw an InterruptedException.
Thread class and its methods
⚫ Notice the output produced when Thread
object is used as an argument to println( ).
This display the name of the thread, its
priority, and the name of its group. By
default, the name of the main thread is
main. Its priority is 5, which is the default
value, and main is also the name of the
group of threads to which this thread
belongs. A thread group is a data structure
that controls the state of a collection of
threads as a whole.
Creating a Thread
⚫ Java defines two ways in which this can be
accomplished:
You can implement the Runnable interface.
You can extend the Thread class.
⚫ The easiest way to create a thread is to
create a class that implements the Runnable
interface. To implement Runnable, a class
need only implement a single method called
run( ), which is declared like this:
public void run( )
{ //code }
Creating a Thread
⚫ Inside run( ), you will define the code that
constitutes the new thread. It is important
to understand that run( ) can call other
methods, use other classes, and declare
variables, just like the main thread can.
⚫ The only difference is that run( ) establishes
the entry point for another, concurrent
thread of execution within your program.
This thread will end when run( ) returns.
Creating a Thread
⚫ After you create a class that implements
Runnable, you will instantiate an object of
type Thread from within that class. Thread
defines several constructors. The one that
we will use is shown here:
Thread(Runnable threadOb, String threadName)
⚫ In this constructor, threadOb is an instance
of a class that implements the Runnable
interface. This defines where execution of
the thread will begin. The name of the new
thread is specified by threadName.
Creating a Thread
⚫ After the new thread is created, it will not
start running until you call its start( )
method, which is declared within Thread. In
essence, start( ) executes a call to run( ).
The start( ) method is shown here:
void start( )
Creating a Thread
⚫ Syntax:
class classname implements Runnable
{
public void run()
{
//write the code for child thread
}
}
Creating a Thread
class classname
{
public static void main(String []args)
{
//create object for the class which
implements runnable interface
//create object for Thread class and pass
object of class which implements runnable
interface as parameter
//call start() method using Thread object
}}
Creating a Thread
⚫ The second way to create a thread is to
create a new class that extends Thread, and
then to create an instance of that class. The
extending class must override the run( )
method, which is the entry point for the
new thread. It must also call start( ) to begin
execution of the new thread.
⚫ Example to be discussed
Creating a Thread
⚫ Syntax:
class classname extends Thread
{
public void run()
{
//write the code for child thread
}
}
Creating a Thread
class classname
{
public static void main(String []args)
{
//create object for the class which extends
Thread class
//call start() method using object
}}

(or)
Creating a Thread
class classname
{
public static void main(String []args)
{
//create object for the class which extends
Thread class
//create object for Thread class and pass
object which extends Thread class as
parameter
//call start() method using Thread class
object } }
Creating Multiple Threads
⚫ So far, you have been using only two
threads: the main thread and one child
thread. However, your program can spawn
as many threads as it needs.
⚫ Example to be discussed
Using isAlive() and join()
⚫ As mentioned, often you will want the main
thread to finish last. In the preceding
examples, this is accomplished by calling
sleep( ) within main( ), with a long enough
delay to ensure that all child threads
terminate prior to the main thread.
⚫ However, this is hardly a satisfactory solution,
and it also raises a larger question: How can
one thread know when another thread has
ended? Fortunately, Thread provides a means
by which you can answer this question.
Using isAlive() and join()
⚫ Two ways exist to determine whether a
thread has finished. First, you can call
isAlive( ) on the thread. This method is
defined by Thread, and its general form is
shown here:
public final boolean isAlive( )
⚫ The isAlive( ) method returns true if the
thread upon which it is called is still running.
It returns false otherwise.
Using isAlive() and join()
⚫ While isAlive( ) is occasionally useful, the
method that you will more commonly use
to wait for a thread to finish is called join( ),
shown here:
final void join( ) throws InterruptedException
⚫ This method waits until the thread on which
it is called terminates. Its name comes from
the concept of the calling thread waiting
until the specified thread joins it.
Using isAlive() and join()
⚫ Syntax:
new_thread_object.isAlive();
new_thread_object.join();
Thread Priorities
⚫ 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
pre-emptive scheduling). But it is not
guaranteed because it depends on JVM
specification that which scheduling it chooses.
⚫ 3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Thread Priorities
⚫ Default priority of a thread is 5
(NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
⚫ The setPriority() method of thread class is
used to change the thread's priority. Every
thread has a priority which is represented
by the integer number between 1 and 10.
Thread Priorities
⚫ public final void setPriority(int newPriority):
java.lang.Thread.setPriority() method
changes the priority of thread to the value
newPriority. This method throws
IllegalArgumentException if value of
parameter newPriority goes beyond
minimum (1) and maximum (10) limit.
⚫ public final int getPriority():
java.lang.Thread.getPriority() method
returns priority of given thread.
Synchronization
⚫ Synchronization in java is the capability to
control the access of multiple threads to
any shared resource. Java Synchronization is
better option where we want to allow only
one thread to access the shared resource.
⚫ The synchronization is mainly used to
◦ To prevent thread interference.
◦ To prevent consistency problem.
⚫ There are two types of synchronization
◦ Process Synchronization
◦ Thread Synchronization
Synchronization
⚫ Here, we will discuss only thread
synchronization.
⚫ There are two types of thread
synchronization namely mutual exclusive
and inter-thread communication.
⚫ Mutual Exclusive helps keep threads from
interfering with one another while sharing
data. This can be done by two ways in java:
◦ by synchronized method
◦ by synchronized block
Synchronization
⚫ 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.
Synchronization
⚫ If you declare any method as synchronized,
it is known as synchronized method.
Synchronized method is used to lock an
object for any shared resource. When a
thread invokes a synchronized method, it
automatically acquires the lock for that
object and releases it when the thread
completes its task.
Synchronization
⚫ Syntax:
synchronized returntype methodname(list)
{
//code
}
Synchronization
⚫ Synchronized block can be used to perform
synchronization on any specific resource of
the method.
⚫ Suppose you have 50 lines of code in your
method, but you want to synchronize only 5
lines, you can use synchronized block.
⚫ If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
Synchronization
⚫ Synchronized block is used to lock an object
for any shared resource.
⚫ Scope of synchronized block is smaller than
the method.
⚫ Syntax:
synchronized (object_reference)
{
//code block
}
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
(wait()) running in its critical section
(Monitor) 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:
Inter-Thread Communication
◦ wait()
◦ notify()
◦ notifyAll()
⚫ wait() method - Causes current thread to release
the lock and wait until either another thread
invokes the notify() method or the notifyAll()
method for this object, or a specified amount of
time has elapsed.
Syntax:
public final void wait() throws InterruptedException
public final void wait(long timeout) throws
InterruptedException
Inter-Thread Communication
⚫ notify() method - Wakes up a single thread that is
waiting on this object's monitor. If many threads
are waiting on this object, one of them is chosen
to be awakened. The choice is arbitrary and occurs
at the discretion of the implementation.
Syntax:
public final void notify()
⚫ notifyAll() method - Wakes up all threads that are
waiting on this object's monitor.
Syntax:
public final void notifyAll()
Inter-Thread Communication
Inter-Thread Communication
⚫ The point to point explanation of the above diagram
is as follows:
◦ Threads enter to acquire lock.
◦ Lock is acquired by one 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.
Inter-Thread Communication
⚫ Why wait(), notify() and notifyAll() methods are
defined in Object class not Thread class? It is
because they are related to lock and object has a
lock.
Inter-Thread Communication
⚫ Producer-Consumer problem –
◦ In computing, the producer–consumer
problem (also known as the bounded-buffer
problem) is a classic example of a
multi-thread synchronization problem. The
problem describes two threads, the producer
and the consumer, who share a common,
fixed-size buffer used as a queue.
◦ The producer's job is to generate data, put it
into the buffer, and start again. At the same time,
the consumer is consuming the data (i.e.,
removing it from the buffer), one piece at a
time.
Inter-Thread Communication
◦ The problem is to make sure that the
producer won't try to add data into the
buffer if it's full and that the consumer won't
try to remove data from an empty buffer.
◦ The solution for the producer is to either go
to sleep or discard data if the buffer is full.
◦ The next time the consumer removes an
item from the buffer, it notifies the producer,
who starts to fill the buffer again.
Inter-Thread Communication
◦In the same way, the consumer can go to
sleep (wait()) if it finds the buffer empty.
◦The next time the producer puts data into
the buffer, it wakes up (notify()) the
sleeping consumer.
◦The solution can be reached by means
of inter-thread communication, typically
using synchronization.
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.
⚫ Deadlock describes a situation where two or
more threads are blocked forever, waiting for each
other.
⚫ Deadlock occurs when multiple threads need the
same locks but obtain them in different order.
Deadlock
⚫ A Java multithreaded program may suffer from the
deadlock condition because
the synchronized keyword causes the executing
thread to block while waiting for the lock, or
monitor, associated with the specified object.

You might also like