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

UNIT-5 new

Multithreading allows a program to execute multiple threads concurrently, enabling simultaneous task execution and improving performance. It differentiates between process-based and thread-based multitasking, with threads being lightweight and sharing the same address space. Key concepts include thread states, creation methods, synchronization, thread priorities, and inter-thread communication, which are essential for managing concurrent operations effectively.

Uploaded by

ushanagsamsani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

UNIT-5 new

Multithreading allows a program to execute multiple threads concurrently, enabling simultaneous task execution and improving performance. It differentiates between process-based and thread-based multitasking, with threads being lightweight and sharing the same address space. Key concepts include thread states, creation methods, synchronization, thread priorities, and inter-thread communication, which are essential for managing concurrent operations effectively.

Uploaded by

ushanagsamsani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Multithreading

Multithreading

• A program can be divided into a number of small processes. Each small process
can be addressed as a single thread (a lightweight process). Multithreaded
programs contain two or more threads that can run concurrently. This means that
a single program can perform two or more tasks simultaneously. For example,
one thread is writing content on a file at the same time another thread is
performing spelling check.
• An instance of Thread class is just an object, like any other object in java. But a
thread of execution means an individual "lightweight" process that has its own
call stack. In java each thread has its own call stack.
• A Process consists of the memory space allocated by the operating
system that can contain one or more threads. A thread cannot exist
on its own; It must be a part of process.
• There are two distinct types of Multitasking i.e., Processor-based and
Thread-based Multitasking.
• What is the difference between thread based and processor-based Multitasking
Difference between Multi tasking and Multi threading
• 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.
• There are two distinct types of multitasking: process-based and thread-based.
• A process is a program that is executing. Thus, process-based multitasking is the
feature that allows to run two or more programs concurrently. For example,
process-based multitasking enables you to run the Java compiler at the same
time that you are using a text editor.
• In process-based multitasking, a program is the smallest unit of code that can be
dispatched by the scheduler.
• 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.
• Thus, process-based multitasking deals with the “big picture,” and thread-based
multitasking handles the details.
• Multitasking threads require less overhead than multitasking processes.
Processes are heavyweight tasks that require their own separate address spaces.
Inter process communication is expensive and limited. Context switching from
one process to another is also costly.
• 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. This is especially
important for the interactive, networked environment in which Java operates,
because idle time is common.
Benefits of Multithreading
1. Enables programmers to do multiple things at one time
2. Programmers can divide a long program into threads and execute them in
parallel which eventually increases the speed of the program execution
3. Improved performance and concurrency
4. Simultaneous access to multiple applications
Thread
• Definition: Thread is a tiny program running continuously. It is sometimes called
as light- weight process.
A thread can be in any of the five following states
1. Newborn State: When a thread object is created a new thread is
born and said to be in Newborn state.
2. Runnable State: If a thread is in this state it means that the thread is
ready for execution and waiting for the availability of the processor. If
all threads in queue are of same priority then they are given time
slots for execution in round robin fashion
3. Running State: It means that the processor has given its time to the
thread for execution. A thread keeps running until the following
conditions occurs
a. Thread give up its control on its own and it can happen in the following
situations
i. A thread gets suspended using suspend() method which can only be
revived with resume() method
ii. A thread is made to sleep for a specified period of time using sleep(time)
method, where time in milliseconds
iii. A thread is made to wait for some event to occur using wait () method. In
this case a thread can be scheduled to run again using notify () method.
b. A thread is pre-empted by a higher priority thread
4. Blocked State: If a thread is prevented from entering into runnable state and
subsequently running state, then a thread is said to be in Blocked state.
5. Dead State: A runnable thread enters the Dead or terminated state when it
completes its task or otherwise terminates.
The main thread

• Even if you don't create any thread in your program, a thread called
main thread is still created. Although the main thread is automatically
created, you can control it by obtaining a reference to it by calling
currentThread() method.
• Two important things to know about main thread are,
• It is the thread from which other threads will be produced.
• main thread must be always the last thread to finish execution.
Creating a thread

• Java defines two ways by which a thread can be created.


• By implementing the Runnable interface.
• By extending the Thread class.
Implementing the Runnable Interface

• The easiest way to create a thread is to create a class that implements


the runnable interface. After implementing runnable interface , the
class needs to implement the run() method, which is of form,
public void run()
• run() method introduces a concurrent thread into your program.
This thread will end when run() returns.
• You must specify the code for your thread inside run() method.
• run() method can call other methods, can use other classes and
declare variables just like any other normal method.
To call the run() method, start() method is used. On calling start(), a new stack is provided to
the thread and run() method is called to introduce the new thread into the program.
Extending Thread class

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

• In this case also, as we must override


the run() and then use the start()
method to start and run the thread.
• Can we start a thread twice?
• No, if a thread is started it can never be started again, if you do so, an
illegalThreadStateException is thrown. Example is shown below in which a same
thread is coded to start again
Interrupting threads

• Stopping a thread: A thread can be stopped from running further by


issuing the following statement-
th.stop();
By this statement the thread enters in a dead state. From
stopping state a thread can never return to a runnable state.
• Use of stop() Method
The stop() method kills the thread on execution
Blocking a thread

• A thread can be temporarily stopped from running. This is called


blocking or suspending of a thread. Following are the ways by which
thread can be blocked
1. sleep( )
By sleep method a thread can be blocked for some specific
time. When the specified time gets elapsed then the thread can
return to a runnable state.
2. suspend( )
By suspend method the thread can be blocked until further
request comes. When the resume() method is invoked then the
returns to a runnable state.
3. wait()
The thread can be made suspended for some specific
conditions. When the notify() method is called then the blocked
thread returns to the runnable state.
• The difference between the suspending and stopping thread is that if
a thread is suspended then its execution is stopped temporarily and it
can return to a runnable state. But in case, if a thread is stopped then
it goes to a dead state and can never return to runnable state.
Suspending Resuming and Stopping of Threads
• In Java 1.1, the following three methods are defined
• suspend() - pause the operation of thread
• resume() - resume the operation of thread
• stop() - to terminate the thread
• These direct methods are very convenient to control the operation of threads in a
multithread environment.
• However, in some situations, they may crash the program or cause serious
damage to critical data.
• For example, if a thread has got the lock to a critical synchronized section of code
and gets suspended, it will not release the lock for which other threads may be
waiting.
• Instead of methods suspend() and resume(), the methods wait() and notify() are
used.
Thread Priorities

• There are various properties of threads. Those are,


1. Thread priorities
2. Daemon Threads
3. Thread group
1. Thread Priorities:
Every thread has a priority that helps the operating system determine the order
in which threads are scheduled for execution. In java thread priority ranges between,
1. MIN-PRIORITY (a constant of 1)
2. MAX-PRIORITY (a constant of 10)
3. By default every thread is given a NORM-PRIORITY(5).
The main thread always have NORM-PRIORITY.

• Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and very much platform dependent.
• The actual allocation is done by the scheduler. Thus, a thread with higher priority
has higher chance getting the CPU and also a higher share of CPU time. Keeping
equal priority for all threads ensures that each has equal chance to share CPU
time, and thus, no thread starves, because when a thread with higher priority
enters the Runnable state, the operating system may pre-empt the scheduling by
allocating CPU to the thread with higher priority.
• When this thread returns from sleep or wait state, the same story may be
repeated. When several threads of different priorities are present, it is quite likely
that a thread with the lowest priority may not get a chance to possess CPU. This
is called starvation.
• Thread priority can be changed by method setPriority (n).
• The priority may be obtained by calling getPriority() method.
2. Daemon Thread:
In Java, any thread can be a Daemon thread. Daemon threads are like a
service providers for other threads. Daemon threads are used for background
supporting tasks and are only needed while normal threads are executing.
• If normal threads are not running and remaining threads are daemon threads
then the interpreter exits.
• setDaemon(true/false) ? This method is used to specify that a thread is
daemon thread.
• public boolean isDaemon() ? This method is used to determine the thread is
daemon thread or not.
• The core difference between user threads and daemon threads is that the JVM
will only shut down a program when all user threads have terminated. Daemon
threads are terminated by the JVM when there are no longer any user threads
running, including the main thread of execution. Use daemons as the minions
they are.
3. Synchronization
When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread
synchronization.
• The synchronized keyword in Java creates a block of code referred to as a critical
section. Every Java object with a critical section of code gets a lock associated
with the object. To enter a critical section, a thread needs to obtain the
corresponding object's lock.
synchronized(object) {
// statements to be synchronized
}
• Problem without using Synchronization
In the following example method updatesum() is not synchronized and
access by both the threads simultaneously which results in inconsistent output.
Making a method synchronized, Java creates a “monitor” and hands it over to the
thread that calls the method first time.
• As long as the thread holds the monitor, no other thread can enter the
synchronized section of the code. Writing the method as synchronized will make
one thread enter the method and till execution is not complete no other thread
can get access to the method.
Here the count should be 10000, but
it is printing less than 10000. To
solve this problem, add synchronized
keyword to the increment() method
as shown in the following code.
Deadlock and Race Situations

• In a multithreaded program, the race and deadlock conditions are common


when improperly synchronized threads have a shared data source as their
target.
• A race condition may occur when more than one thread tries to execute
the code concurrently. A thread partly does the job when the second thread
enters.
• If the process is atomic, that is, it cannot be subdivided the effect of race
condition will be limited.
• However, when the process is not atomic and can be subdivided into two or
more sub-processes, it may occur that a thread has done subprocess, and
the second thread enters and starts executing. In such cases, the results can
be far from the desired ones.
• Therefore, a race condition is a situation in which two or more
threads try to execute code and their actions get interleaved. The
solution for such condition is the synchronization, and therefore, only
one thread should enter code at a time and others should wait until
the first has done its job.
• In multithreaded programs, the deadlock conditions are also common
• A deadlock condition may lead to program crash. Such a situation
occurs when two threads are attempting to carry out synchronized
hods that are inter-dependent, that is, the completion of Method1
needs Method2 and completion of Method2 needs Method1.
Inter thread Communication
It is all about making synchronized threads communicate with each other. It
is a mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter in the same critical section to be executed.
These method are implemented as final in Object. All three method can be called
only from within a synchronized context. It is implemented by the following
methods of Object Class:
• wait( ): This method tells the calling thread to give up the monitor and go to sleep
until some other thread enters the same monitor and calls notify( ).
• notify( ): This method wakes up the first thread that called wait( ) on the same
object.
• notifyAll( ): This method wakes up all the threads that called wait( ) on the same
object. The highest priority thread will run first. These methods are implemented
as final methods in Object, so all classes have them. All three methods can be
called only from within a synchronized context.
Difference between wait() and sleep()

You might also like