0% found this document useful (0 votes)
6 views30 pages

CSC 211 MultiThreading

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)
6 views30 pages

CSC 211 MultiThreading

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

Multithreading

BY MR. TARUS
MULTITASKING
 The process of executing multiple tasks simultaneously / concurrently.
 Multitasking is used to utilize resources e.g., CPU, Main memory etc.
 With a single CPU only one task can be running at one point of time, so CPU uses
context switching to perform multitasking. Context switch (Context means state)
is the process of storing and restoring the state of a process so that execution can
be resumed from the same point at a later time.

Example:
 class room student is:
Listening
Writing
 Executing multiple tasks at a time by executing them concurrently over a specified
period.
Multitasking is done in two ways.
1. Process-based multitasking: (Multiprocessing)
 Executing multiple tasks simultaneously, where each task is separate independent
process or program.
 Each process has its address in memory, i.e., each process allocates separate
memory area.
 Type of multitasking based upon processes i.e. context switching is done in-
between processes. For example: Typing in notepad, Listening music and
downloading file from internet at the same time. (all applications are independent).
 Type of multitasking which is handled at operating system level.
Process:
 A program in execution.
 An instance of a program in execution
 A process has a self-contained execution environment i.e. allocates separate memory
area. Context switch time is more in case of processes because switch is done between
different memory areas.
2. Thread-based multitasking: (Multithreading)
 Termed as multithreading where threads share the same address space.
 Executing multiple tasks simultaneously, where each task is a separate
independent part of the same program or process.
 Each independent part is called a thread.
 Type of multitasking based upon threads i.e. context switching is done in-
between threads.
 In Multithreading, multiple independent tasks are executed simultaneously.
These independent tasks are the part of same application. Multithreading is the
type of multitasking which is handled at program level.
Thread:
 A thread is a lightweight process.

 A single sequence of execution within a program.

 Thread uses process’s execution environment i.e. memory area. Context switch
time is less in case of threads because switch is done within the same process’s
memory area.
 A thread represents a flow of execution. Every thread has a job associated with it.

 Note: A thread can’t exist without process, it exist within the process.
 Let program has 10k lines of code.

 Last 5k lines does not depend on 1st 5k lines.

 Let all threads start simultaneously.

 Nb: takes less time as opposed to it being


single program.
 Nb:

 Any type of multitasking is used to reduce


response time of system and improves
performance.
Difference between thread and process in Java
Process Thread
1. Process has its own main memory 1. Thread use process’s main memory
for execution. for execution and share it with other
threads.
2. Process is considered as 2. Thread is considered as lightweight
heavyweight component. component.
3. One process can have multiple 3. One thread can’t have multiple
threads. process.
4. Context switch time is more. 4. Context switch time is less.
Multithreading
The process of executing multiple threads simultaneously.

Multiprocessing and multithreading are used to achieve multitasking.

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.
 A thread is executed inside a process.

 There can be multiple processes in o/s.

 A single process can have multiple threads.


Benefits of Multithreading
 Resource Sharing:
All the threads of a process share its resources such as memory, data, files etc. A
single application can have different threads within the same address space using
resource sharing.
 Responsiveness:
Program responsiveness allows a program to run even if part of it is blocked using
multithreading. This can also be done if the process is performing a lengthy
operation. For example - A web browser with multithreading can use one thread
for user contact and another for image loading at the same time.
 Better Communication
Thread synchronization functions could be used to improve inter-process
communication. Moreover, sharing huge amounts of data across multiple threads
of execution inside the same address space provides extremely high-bandwidth,
low-latency communication across various tasks within an application.
 Utilization of Multiprocessor Architecture:
In a multiprocessor architecture, each thread can run on a different processor in
parallel using multithreading. This increases concurrency of the system. This is in
direct contrast to a single processor system, where only one process or thread can
run on a processor at a time.
 Economy:
It is more economical to use threads as they share the process resources.
Comparatively, it is more expensive and time-consuming to create processes as
they require more memory and resources. The overhead for process creation and
management is much higher than thread creation and management.
 Scalability
The advantages of multi-programming become much more apparent in the case of
multiprocessor architecture, when threads may execute in parallel on many
processors. When there is just one thread, it is impossible to break the processes
into smaller jobs performed by different processors.
A single-threaded process could only run on one processor, despite the number of
processors available. Multithreading on multiple CPU machines increases
parallelism.
 Parallel Programming
One of the main reasons to use threads in Java is to make a task run parallel to
another task like drawing and event handling.GUI applications e.g. Swing and
Java FX GUIs are the best examples of multi-threading in Java. In a typical GUI
application, the user initiates an action like downloading a file from the network
or loading games modules from a hard disk.
 To serve multiple clients at the same time.
One of the most common scenarios where using multiple threads significantly
improves an application's performance is a client-server application. A single-
threaded application means only one client can connect to the server at a time, but
a multi-threaded server means multiple clients can connect to the server at the
same time.

Disadvantages of Multithreading
 There are various disadvantages of multithreading in the operating system, and some
of the disadvantages are as follows:
 It needs more careful synchronization (crucial for ensuring that multiple threads
operate safely on shared resources.).
 It can consume a large space of stocks of blocked threads.

 It needs support for thread or process.

 If a parent process has several threads for proper process functioning, the child
processes should also be multithreaded because they may be required.

Application areas of Multithreading
 To develop multimedia movies.

 To develop video games.

 To develop web servers (Apache HTTP Server, Nginx, ) and application servers
(JBoss , Glassfish, Apache Tomcat, Node.js) etc
Thread Life Cycle
 Refers to the state transformations of a thread that begins with its birth and ends
with its death. When a thread instance is generated and executed by calling the
start() method of the Thread class, the thread enters the runnable state. When the
sleep() or wait() methods of the Thread class are called, the thread enters a non-
runnable mode.
 Thread returns from non-runnable state to runnable state and starts statement
execution. The thread dies when it exits the run() process. In Java, these thread
state transformations are referred to as the Thread life cycle.
 There are basically 4 stages in the lifecycle of a thread, as given below:
New
Runnable
Running
Blocked (Non-runnable state)
Dead
1. New State:
 A new instance of the thread is created.
 E.g., MyThread t = new MyThread();
2. Runnable:
 The thread is ready to execute after invocation of start() method.
3. Running
 The thread is running by using run() method.
4. No-runnable: (Blocked)
 The thread is in blocked state. i.e., the thread is still alive but not eligible to
run.
5. Terminated (Dead).
 Thread is in dead state. When run() method exits or completes the process.
Thread class
 Provides methods and constructors to create and perform operations on a thread.
 Commonly used methods of a thread class are:
• public void run() : Used to perform action for a thread.
• public void start() : Used to start execution of a thread. JVM calls the run() on
the thread
• public void sleep() : Stops the execution of the thread for the specified
number of milliseconds.
• public void setName() : (string name). Used to set or changes the name of
thread
• public void getName() : Used to get name of the thread.
• public void setPriority() : (int priority) Used to set or change the priority of
the thread.
• public int getPriority() : Returns the priority of the thread.
Pto…
• public Boolean isAlive() : Checks if the thread is alive or not.

• public void yield() : Used to pause the currently executing thread and allow
other threads to execute.

• public void suspend() : Used to suspend the thread.

• public void resume() : Used to resume the suspended thread.

• public void stop : Used to stop the executing of a thread.


Thread Constructors

 Thread() : Without parameters / arguments.


 Thread(String name) : With one string argument.
 Thread(Runnable r) : With runnable argument.
 Thread(Runnable r, String name) : with runnable and string arguments.

 Nb: Runnable:

 An interface that is to be implemented by a class whose instances are intended to


be executed by a thread
Creating a Thread SimpleThread.java, MutlithreadingDemo.java
 Two ways of creating a Thread:
1. By extending Thread class (use example) ThreadDemoApp1.java
2. By implemeting Runnable interface.
1. By extending Thread class
Syntax:
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
Nb:
 We can use run() and start() in Thread class
2. By implementing Runnable interface.
 By implementing runnable interface, we can be able to create and execute a thread.
 Runnable interface should be implemented by any class.
 Runnable interface have only one thread method named run(), where run() method is
abstract method.
 Programmer should declare object for subclass, that object can be used as argument in the
Thread class constructor from thread object.
• Syntax:
class class_name implements Runnable
{
Public void run()
{
--
}
} Multi3.java, MultiThread1.Java, ThreadState.java, TestThread.java,
Thread Priority
Thread Scheduler:
 Component of Java that decides which thread to run or execute and which thread
to wait.
 In Java, a thread is only chosen by a thread scheduler if it is in the runnable state.

 Criteria that decide which thread will execute first. There are two factors for
scheduling a thread i.e. Priority and Time of arrival.
 Priority : ThreadDemoPriority.java, Apriority.java, MyThread.java
 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 priority.
 But is not guaranteed because it depends on JVM specifications that which
scheduling it chooses.
 There are three constant thread priorities defined in the Thread class.
 public static int MIN_PRIORITY. //value is 1.
 public static int NORM_PRIORITY //value is 5
 public static int MAX_PRIORITY //value is 10
 Time of arrival:
 Suppose two threads of the same priority enter the runnable state, then priority
cannot be the factor to pick a thread from these two threads. In such a
case, arrival time of thread is considered by the thread scheduler. A thread that
arrived first gets the preference over the other threads.
Methods of a Thread class
 activeCount() Returns an estimate of the number of active threads in the
current thread’s thread group and its subgroups
 checkAccess() Determines if the currently running thread has permission to
modify this thread.
 clone() Throws CloneNotSupportedException as a Thread can not be
meaningfully cloned.
 currentThread() Returns a reference to the currently executing thread object.
 dumpStack() Prints a stack trace of the current thread to the standard error
stream.
 getId() Returns the identifier of this Thread
 getName() Returns this thread’s name
 getPriority() Returns this thread’s priority
 getState() Returns the state of this thread
TestThreadMethods.java
 isAlive() Tests if this thread is alive
 isInterrupted() Tests whether this thread has been interrupted
 join() Waits for this thread to die
 run()
 start() Causes this thread to begin execution; the Java Virtual Machine
calls the run method of this thread
 yield() A hint to the scheduler that the current thread is willing to yield
its current use of a processor
 sleep() Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds,
subject to the precision and accuracy of system timers and
schedulers
Synchronization
 The capability to control the access of multiple threads to any shared resource.
 In the Multithreading concept, multiple threads try to access the shared resources
at a time to produce inconsistent results.
 Therefore, synchronization is necessary for reliable communication between
threads.
 Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
 The synchronization is mainly used to
a. To prevent thread interference.
b. To prevent consistency problem.
 Types of synchronization:
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
• Two types of thread synchronization are:
1. Mutual Exclusive
• Synchronized method.
• Synchronized block.
• Static synchronization.
• Nb: Mutual Exclusive helps keep threads from interfering with one another while
sharing data. It can be achieved by using the above mentioned three ways:
• 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.
• From Java 5 the package java.util.concurrent.locks contains several lock
implementations.
2. Cooperation (Inter-thread communication in java)
1. Understanding the problem without Synchronization
 TestSynchronization.java

 In this example, there is no synchronization, so output is inconsistent.

2. Java Synchronized Method: TestSynchronization2.java


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

You might also like