You are on page 1of 17

Chapter 5

Multi-threading concept

1 Advanced java By Abdu A. 09/09/2023


Introduction
 An executing program itself is called a process.
 It can be explained with an example say when you click on any application,
and it starts we can say that a process has been started.
 Every process has its own address space hence, they do not overlap each
other.
 In a process-based multitasking, more than two processes can run
simultaneously on the computer.
 A process can contain multiple threads, where every thread is responding
different request of the user.
 Process are also called heavyweight task.
 Process-based multitasking leads to more overhead.
 Inter-process communication is very expensive and limited.
 Switching from one process to also expensive.
 Java does not control the process based multitasking.
2 Advanced java By Abdu A. 09/09/2023
Cont.…
 The threads are extensively used in Java-enabled
browsers. A thread is a part of a process. A process can
contain multiple threads. These multiple threads in a
process share the same address space of the process.
 Each thread has its own stack and register to operate on.
 Threads are also called lightweight task.
 The overhead of the thread-based multitasking is very
low.
 The cost of inter-thread communication and context
switching from one thread to another thread is very low.
 Multithreaded multitasking is under the control of Java.

3 Advanced java By Abdu A. 09/09/2023


Thread vs process

4 Advanced java By Abdu A. 09/09/2023


5 Advanced java By Abdu A. 09/09/2023
Key Differences Between Process and Thread in Java
 A process is an executing program whereas, the thread is a small part of a process.
 Each process has its own address space whereas, the threads of the same process
share the address space as that of the process.
 In process based multitasking, more than two processes can run at the same time
whereas, in thread-based multitasking, more than two thread can run at the same
time.
 Inter-process communication between two processes is costlier than inter-thread
communication.
 Context switching between two processes is expensive and limited as compared to
context switching between two threads.
 A process is also called the heavyweight task whereas, the thread is called
lightweight task.
 Multitasking over a process is not under the control of Java whereas, the
Multitasking over multithreading is under the control of Java.
 Components contained by a process its own address space, global variables, signal
handlers, open files, child processes, accounting information. On the other hand, a
thread contains its own register, state, stack, program counter.
6 Advanced java By Abdu A. 09/09/2023
Multiple threads
 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.
 Multi-threading extends the idea of multitasking into applications where
you can subdivide specific operations within a single application into
individual threads. Each of the threads can run in parallel. The OS divides
processing time not only among different applications, but also among each
thread within an application.
 Threads can be created by using two mechanisms : 
 Extending the Thread class 
 Implementing the Runnable Interface
 Threads allow a program to operate more efficiently by doing multiple
things at the same time performing complicated tasks in the background
without interrupting the main program execution.

7 Advanced java By Abdu A. 09/09/2023


Thread priorities
 Every Thread in java has a priority. It may be the default priority assigned
by the JVM or a customized priority explicitly provided by the programmer.
In a multi-threaded environment, the thread scheduler uses the priorities
while allocating processors to the threads for their execution. However,
thread priorities cannot guarantee the order in which threads execute and are
very much platform dependent.
 Each thread has a priority. Priorities are represented by a number between 1
and 10. In most cases, the 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.
 Note that not only JVM, a Java programmer can also assign the priorities of
a thread explicitly in a Java program.
 The Thread having the highest priority will be executed first followed by
other low priority threads waiting for their execution. This means the
scheduler gives preference to high-priority threads.

8 Advanced java By Abdu A. 09/09/2023


Cont.…
 If multiple threads are having same priority, then the
execution order of the threads will be decided by the
thread scheduler based on some internal algorithm,
either round robin, preemptive scheduling, or FCFS (First
Come First Serve) algorithm. The thread scheduler is part
of the JVM and varies from JVM to JVM and hence we
can’t expect the exact algorithm used by the scheduler.

9 Advanced java By Abdu A. 09/09/2023


Cont.…
 3 constants defined in Thread class:
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY
 Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
 Setter & Getter Method of Thread Priority
 public final int getPriority(): The java.lang.Thread.getPriority()
method returns the priority of the given thread.
 public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or assign the priority of
the thread to newPriority.
 The method throws IllegalArgumentException if the value newPriority
goes out of the range, which is 1 (minimum) to 10 (maximum).
10 Advanced java By Abdu A. 09/09/2023
Thread synchronization
 Thread Synchronization is a process of allowing only one thread to use the
object when multiple threads are trying to use the particular object at the
same time.
 To achieve this Thread Synchronization we have to use a java keyword or
modifier called “synchronized”.
 Synchronization in java is the capability to control the access of multiple
threads to any shared resource. It is a better option where we want to allow
only one thread to access the shared resource.
 Why use Synchronization?
 The synchronization is mainly used to :
 If you start with at least two threads inside a program, there might be a
chance when multiple threads attempt to get to the same resource. It can even
create an unexpected outcome because of concurrency issues. 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.

11 Advanced java By Abdu A. 09/09/2023


Cont.…
 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.
 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.

12 Advanced java By Abdu A. 09/09/2023


Types of Thread Synchronization
 There are two types of Thread Synchronization. They are:
 MutualExclusive
 Cooperation (Inter-Thread Communication) 

 Mutual Exclusive:
 Mutual Exclusive helps keep threads from interfering with
one another while sharing data. Mutual Exclusion can be
achieved in three ways in java:
 Synchronized Method
 Synchronized Block
 Static Synchronization

13 Advanced java By Abdu A. 09/09/2023


Thread Synchronization using Synchronized Method in Java:
 Method level synchronization is used for making a method
code thread-safe, i.e. only one thread must be executing this
method code.
 Syntax :
<access modifier> synchronized method ( parameter)
{
    //synchronized code
}
  In the case of the synchronized method, the lock object is:
 class object – if the given method is static.
 this object – if the method is non-static. ‘this’ is the reference to
the current object in which the synchronized method is invoked.

14 Advanced java By Abdu A. 09/09/2023


Thread Synchronization using Synchronized Block in Java:
 Block-level synchronization is used for making some
amount of method code thread-safe. If we want to
synchronize access to an object of a class or only a part of
a method to be synchronized then we can use the
synchronized block for it.
 It is capable to make any part of the object and method
synchronized.
 Syntax:
synchronized (object reference expression) {   
  //code block   
}

15 Advanced java By Abdu A. 09/09/2023


Thread Synchronization using Static Synchronized in Java:
 In simple words, a static synchronized method will lock
the class instead of the object, and it will lock the class
because the keyword static means: “class instead of
instance”. The keyword synchronized means that only one
thread can access the method at a time. And static
synchronized mean: Only one thread can access the class
at one time.

16 Advanced java By Abdu A. 09/09/2023


Thank you !!

17 Advanced java By Abdu A. 09/09/2023

You might also like