UNIT-5 new
UNIT-5 new
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
• 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