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

Chapter 2 - Multi Threading

The document provides an overview of multithreading in programming, explaining its significance in enhancing parallel processing and user response. It details the life cycle of a thread, methods for creating and managing threads, and addresses synchronization issues, including the producer-consumer problem. Additionally, it covers thread priorities and daemon threads, emphasizing their roles in a multithreaded environment.

Uploaded by

waif
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)
15 views

Chapter 2 - Multi Threading

The document provides an overview of multithreading in programming, explaining its significance in enhancing parallel processing and user response. It details the life cycle of a thread, methods for creating and managing threads, and addresses synchronization issues, including the producer-consumer problem. Additionally, it covers thread priorities and daemon threads, emphasizing their roles in a multithreaded environment.

Uploaded by

waif
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/ 34

Multi Threading

Mettu University
Department of Information Technology
3rd Year
Advanced Programming – Chapter 2
Introduction

• The modern operating system such as windows 95 may


recognize that they can execute several programs
simultaneously. This ability is known as multitasking.
In system’s terminology, it is called Multithreading.

• Multithreading is a conceptual programming paradigm


where a program is divided into two or more subprograms
(processes), which can be implemented at the same time
in parallel.

Example:
• one program can display an animation on the screen
while another may build the next animation to be
displayed. This is something similar to dividing a task
into subtasks and assigning them to different people
for execution independently and simultaneously.
Multitasking and Multithreading
• Multitasking:
– refers to a computer's ability to perform multiple
jobs concurrently
– more than one program are running concurrently, e.g.,
UNIX
• Multithreading:
– A thread is a single sequence of execution within a
program
– refers to multiple threads of control within a single
program
– each program can run multiple threads of control
within it, e.g., Web Browser
Concurrency vs. Parallelism
CPU CPU1 CPU2
Single threaded Vs Multithreaded

Single-Threaded:
A Thread is similar to a program that has a single
flow of control. It has a beginning, a body and an
end. And executes commands sequentially. In fact
all main programs in our earlier examples can be
called single-threaded programs.

Multithreading:
Java enable us to use multiple flows of control in
developing programs. Each flow of control may be
thought of as a separate tiny program known as a
thread that runs in parallel to others.

Cont..
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded environment, the
web server can serve multiple request
simultaneously thus improving response time
Creating Threads
• There are two ways to create our own Thread object
1. Sub classing or extending a Thread class and
instantiating a new object of that class
2. Implementing the Runnable interface
• In both cases the run() method should be implemented
Extending Thread
public class ChildThread extends Thread {
public void run () {
for (int i = 1; i <= 100; i++) {
System.out.println(“---”);
}
}
}
Implementing Runnable
public class ChildRunnableThread implements Runnable {
public void run () {
for (int i = 1; i <= 100; i++) {
System.out.println (“***”);
}
}
}
Thread Methods
void start()
– Creates a new thread and makes it runnable
– This method can be called only once
void run()
– The new thread begins its life inside this method
void stop() (deprecated)
– The thread is being terminated
Thread Methods
void yield()
– Causes the currently executing thread object to
temporarily pause and allow other threads to execute
– Allow only threads of the same priority to run
void sleep(int m) or sleep(int m, int n)
– The thread sleeps for m milliseconds, plus n
nanoseconds
Starting New Thread

To actually create and run an instance of our


thread class, we must write the following

Example:
Case 1: If the class extends Thread
ChildThread aThread = new ChildThread( );
aThread.start( ); // Invokes run( )
method.

Case 2: If the class implements Runnable


RunnableThread runnableThread = new RunnableThread();
Thread myThread = new Thread(runnableThread);
myThread.start();
Life Cycle of a Thread

During the life time of a thread, there are


many states it can enter. They include:

1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State

Note : A Thread is always In one of these five states.


It can move from one state to another via a
variety of ways.
State Transition Diagram of a Thread
New Thread Newborn

stop
start
Active Thread

stop
Dead
Running Runnable

yield
Killed
suspend Thread
resume
sleep stop
notify
wait
Blocked Idle Thread
(Not Runnable)
Life Cycle of a Thread
Newborn State:

 When we create a thread object, the thread is born


and is said to be in newborn state. The thread is not
yet scheduled for running.
 At this state, we can do only one of the following
things with it:

 Schedule it for running using start( ) method.


 Kill it using stop( ) method.
Note: If we attempt to use any other method at this stage,
an exception will be thrown.

Newborn

Runnable Cont..
Dead State
State
Life Cycle of a Thread

Runnable State:

 The runnable state means that the thread is ready


for execution and is waiting for the availability of
the processor.
 If all threads have equal priority, then they are
given time slots for execution in round robin
fashion.
 The process of assigning time to threads is known as
time – slicing.

yield

… …

Runnable
Running Thread
Thread Cont..
Life Cycle of a Thread
Running State:
 Running means that the processor has given its time
to the thread for its execution. The Thread runs
until it relinquishes control on its own or it is
preempted by a higher priority thread.
 A running thread may relinquish its control in one
of the following situations.
 It has been suspended using suspend( ) method. A
suspended thread can be revived by using the resume( )
method.

Suspend

resume

Running Runnable Suspende


Thread Thread d
Cont..
Life Cycle of a Thread
 It has been made to sleep. sleep(t)

after t

Running Runnable Sleeping


Thread Thread

 It has been told to wait until some event occurs. This is done using the
wait( ) method. The thread can be scheduled to run using the notify( )
method.
wait

notify

Running Runnable waiting


Thread Thread
Life Cycle of a Thread
Blocked State:
 A thread is said to be blocked when it is prevented
from entering into the runnable state and
subsequently the running state.
 This happens when the thread is suspended, sleeping
or waiting in order to satisfy certain requirements.
 A blocked thread is considered “not runnable” but
not dead and therefore fully qualified to run again.

Dead State:
 Every thread has a life cycle. A running thread ends
its life when it has completed executing its run( )
method. It’s a natural death.
 However, we can kill it by sending the stop message
to it at any state thus causing a premature death to
it.

Cont..
Example
public class PrintThread1 extends Thread {
String name;
public PrintThread1(String name) {
this.name = name;
}
public void run() {
for (int i=1; i<100 ; i++) {
try {
sleep((long)(Math.random() * 100));
} catch (InterruptedException ie) { }
System.out.print(name);
}
}
Example (cont)

public static void main(String args[]) {


PrintThread1 a = new PrintThread1("*");
PrintThread1 b = new PrintThread1("-");

a.start();
b.start();
}
}
Stopping & Blocking Thread

Stopping Thread:

Whenever we want to stop a thread from running further, we may


do so by calling its stop( ) method like:
aThread.stop( );

This statement causes the thread to move to the dead state.

Blocking a Thread:
A thread can also be temporarily suspended or blocked from
entering in to the runnable and subsequently running state by using
either of the following thread methods:
Stopping & Blocking Thread
Blocking a Thread:
A thread can also be temporarily suspended or blocked from
entering in to the runnable and subsequently running state by using
either of the following thread methods:

 sleep( ) // Blocked for a specified time


 suspend( ) // Blocked until further orders
 wait( ) // Blocked until certain condition occurs.

Note: These methods cause the thread to go into the blocked (or not-
runnable) state.
 the tread will return to the runnable state when the specified time is
elapsed in the case of sleep( ).
 The resume( ) method is invoked in the case of suspend( ).
 The notify( ) method is called in the case of wait( ).
Thread Exceptions

 IllegalThreadStateException – Whenever we attempt


to invoke a method that a thread cannot handle in
the given state.

 ThreadDeath – Killed Thread

 IllegalArgumentException – Illegal Method


argument

 InterruptedException – Cannot handle it in the


current state.
Thread Priority
 In Java. Each thread is assigned a priority, which affects the order in
which it is scheduled for running.
 Java permits us to set the priority of a thread using the setPriority( )
method

Syntax:
ThreadName.setPriority(intNumber);

The intNumber is an integer value to which the thread’s priority is set.


The Thread class define several priority Constants:

MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Synchronization
 Consider the Example, one thread may try to read a record from a file
while another is still writing to the same file. Depending on the situation,
we may get strange results.
 Java enables us to overcome this problem using a technique known as
synchronization.

Example Coding :
synchronized void update( )
{
…….
……
}
When we declare 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 code.
Daemon Threads
• Daemon threads are “background” threads, that provide
services to other threads, e.g., the garbage collection
thread
• The Java VM will not exit if non-Daemon threads are
executing
• The Java VM will exit if only Daemon threads are
executing
• Daemon threads die when the Java VM exits
• Q: Is the main thread a daemon thread?
• A: No
Daemon Thread
• To Check the Current Daemon status:
threadObject.isDaemon();
• To set the thread to Daemon thread:
threadObject.setDaemon(true);

• Note: by default, all threads are non-daemon


Producer – Consumer Problem
• In computing, the producer–consumer problem (also known
as the bounded-buffer problem) is a classic example of a
multi-process synchronization problem.

• The problem describes two processes, 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.

• 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.
Producer Consumer - Solution
• 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.
• In the same way, the consumer can go to sleep if it
finds the buffer to be empty. The next time the
producer puts data into the buffer, it wakes up the
sleeping consumer.
• The solution can be reached by means of inter-
process communication,
Example - Producer
boolean status = false;
synchronized int produce(int n)
{
if(status)
try{
wait();
}catch(InterruptedException e){
System.out.println("InterruptedException
caught");
}
this.n = n;
status = true;
System.out.println("Produced:" + n);
notify();
return n;
}
Example - Consumer
synchronized int consume()
{
if(!status)
try
{wait();}
catch(InterruptedException e)
{
System.out.println("InterruptedException
caught");
}
System.out.println("Consumed:" + n);
status = false;
notify();
return n;
}
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy