Unit – 06
Multithreading
Prepared By
Prof. Twinkle bhimani
Assistant Professor, CE Dept.
Contents
• Thread model
• Creating threads
• Thread priorities
• Synchronization
• Inter-thread communication
Concurrency
• Concurrency is the ability to run several programs or several parts of
a program in parallel.
• If a time consuming task can be performed asynchronously or in
parallel, this improves the throughput and the interactivity of the
program.
• A modern computer has several CPU's or several cores within one
CPU.
• Two basic units of execution,
• Processes – it has self contained execution environment. Has its own
memory space.
• Threads – Threads exist within process – every process has at least
one. Threads share process’s resources including memory and open
files.
What is Thread?
• Thread is a tiny program running continuously. It is called as light
weight process. Any single path of execution is called thread.
• A thread is also called flow of execution.
• Switching between threads automatically done by JVM
S.No Thread Process
1. It is a light-weight process It is a heavy-weight process
2 Threads do not require separate Each process requires
address space. It runs in the separate address space to
address space of process to execute.
which it belongs to.
Multithreading vs
Multitasking
S.No Multithreading Multitasking
1. Thread is a fundamental unit of Process is a fundamental unit of
multithreading. multiprocessing environment.
2. Multiple parts of a single program Multiple programs get executed in
gets executed in multithreading envi. multiprocessing envi.
3. During multithreading the processor During multiprocessing the processor
switches b/w multiple threads of the switches b/w multiple programs.
program.
4. It is cost effective because CPU can It is expensive because when a particular
be shared among multiple threads at process uses CPU other processes has to
a time. wait.
5. Highly efficient Less efficient
6. It helps in developing application It helps in developing OS programs.
programs.
Thread states and life
cycle
• A thread state indicates the status of thread.
• Tasks are executed in threads. Threads can be in one of five states:
New, Ready, Running, Blocked, or Finished
Thread states and life
cycle
• When a thread is newly created, it enters the New state. After a thread is started by calling its
start() method, it enters the Ready state. A ready thread is runnable but may not be running
yet. The operating system has to allocate CPU time to it.
• When a ready thread begins executing, it enters the Running state. A running thread can
enter the Ready state if its given CPU time expires or its yield() method is called.
• A thread can enter the Blocked state (i.e., become inactive) for several reasons. It may have
invoked the join(), sleep(), or wait() method. It may be waiting for an I/O operation to finish.
A blocked thread may be reactivated when the action inactivating it is reversed. For
• example, if a thread has been put to sleep and the sleep time has expired, the thread is
reactivated and enters the Ready state.
• Finally, a thread is Finished if it completes the execution of its run() method.
• The isAlive() method is used to find out the state of a thread. It returns true if a thread is in
the Ready, Blocked, or Running state; it returns false if a thread is new and has not started or
if it is finished.
• The interrupt() method interrupts a thread in the following way: If a thread is currently in the
Ready or Running state, its interrupted flag is set; if a thread is currently blocked, it is
awakened and enters the Ready state, and a java.lang.InterruptedException is thrown.
The Thread Class
• The Thread class contains the constructors for creating threads for
tasks and the methods for controlling threads.
Creating Threads
Two approaches,
1. Using Thread class
2. Using Runnable interface
The run() method is the most important method in any thread
programming. Using this method thread behavior can be implemented.
Syntax:
public void run()
{
//statements
}
Creating Threads
//Example using Runnable interface
//Example using Thread class
class mythread implements Runnable
class mythread extends Thread
{
{
public void run()
public void run()
{
{
System.out.println("Thread is created!!");
System.out.println("Thread is
}
created!!");
}
}
class Main extends mythread
}
{
class threaddemo
public static void main(String args[])
{
{
public static void main(String args[])
Main obj = new Main();
{
Thread t= new Thread(obj);
mythread t= new mythread();
t.start();
t.start();
}
}
}
}
Thread Synchronization
• Java Synchronization allows only one thread to access the shared
resource. This will overcome problems like i) Thread interference and ii)
Memory consistency errors. iii) Inconsistency problems.
• The synchronization concept is based on monitor, which is lock and
unlock. When a thread owns this monitor other thread cannot access
the resources. Other threads will be in waiting state.
Two ways to achieve synchronization,
1) Using synchronized methods
2) Using synchronized blocks or statements
Rules:
1. Constructors, Classes and variables cannot be synchronized
2. Each object has one lock
3. A thread can acquire more than one lock.
4. When synchronization applied it is called critical section (one thread process
can access resource at a time).
Thread Synchronization
class Table{ Table t;
synchronized void printTable(int n) { MyThread2(Table t){
this.t=t;
for(int i=1;i<=5;i++){ }
System.out.println(n*i); public void run(){
try{ t.printTable(100);
Thread.sleep(400); }
}catch(Exception e) }
{System.out.println(e);}
} } } class Main{
public static void main(String args[]){
class MyThread1 extends Thread{ Table obj = new Table();//only one
Table t; object
MyThread1(Table t) MyThread1 t1=new MyThread1(obj);
{ this.t=t; } MyThread2 t2=new MyThread2(obj);
public void run() { t1.start();
t.printTable(5); t2.start();
} } } }
Thread Synchronization
Synchronization Non-Synchronization
5 5
10 100
15 200
20 10
25 300
100 15
200 20
300 400
400 500
500 25
Thread Priorities
• Priority of a thread describes how early it gets execution and selected
by the thread scheduler. In Java, when we create a thread, always a
priority is assigned to it.
• In a Multithreading environment, the processor assigns a priority to a
thread scheduler. The priority is given by the JVM or by the programmer
itself explicitly.
• The range of the priority is between 1 to 10 and there are three
constant variables which are static and used to fetch priority of a
Thread.
Thread Priorities
1. public static int MIN_PRIORITY
• It holds the minimum priority that can be given to a thread. The value
for this is 1.
2. public static int NORM_PRIORITY
• It is the default priority that is given to a thread if it is not defined. The
value for this is 5.
3. public static int MAX_PRIORITY
• It is the maximum priority that can be given to a thread. The value for
this is 10.
Thread Priorities
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread Running...");
} P1 thread priority : 5
Thread Running...
public static void main(String[]args) P2 thread priority : 5
P3 thread priority : 5
{
MyThread p1 = new MyThread();
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
p1.start();
System.out.println("P1 thread priority : " + p1.getPriority());
System.out.println("P2 thread priority : " + p2.getPriority());
System.out.println("P3 thread priority : " + p3.getPriority());
}
}
Thread Priorities
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread Running..."); Thread Running...
} max thread priority : 10
min thread priority : 1
public static void main(String[]args) normal thread priority : 5
{
MyThread p1 = new MyThread();
p1.start();
System.out.println("max thread priority : " + p1.MAX_PRIORITY);
System.out.println("min thread priority : " + p1.MIN_PRIORITY);
System.out.println("normal thread priority : " + p1.NORM_PRIORITY);
}
}
Thread Priorities
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread Running...
"+Thread.currentThread().getName());
}
public static void main(String[]args) first thread priority : 2
{ second thread priority : 1
MyThread p1 = new MyThread(); Thread Running... Thread-1
MyThread p2 = new MyThread(); Thread Running... Thread-0
p1.setPriority(10); // Highest priority
p2.setPriority(1); // Low priority
p1.start(); // Starting threads
p2.start();
// Getting and printing priorities
System.out.println("first thread priority : " + p1.getPriority());
System.out.println("second thread priority : " + p2.getPriority()); } }
Inter-Thread Communication –
Cooperation among Threads –
Producer-Consumer Problem
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a
thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed.
It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
Inter-Thread Communication –
Cooperation among Threads –
Producer-Consumer Problem
class Customer {
{ System.out.println("going to deposit...");
int amount=100; this.amount+=amount;
synchronized void withdraw(int amount) System.out.println("Deposit of " + amount+ "
{ completed... ");
System.out.println("Going to withdraw..."); notify();
}
if(this.amount<amount){ }
System.out.println("Less balance; waiting for
deposit..."); class InterThread
try{wait();}catch(Exception e){} {
} public static void main(String args[]){
this.amount-=amount; final Customer c=new Customer();
System.out.println("Withdraw of " +amount+" new Thread(){
completed..."); public void run(){c.withdraw(500);}
} Output: }.start();
Going to withdraw...
Less balance; waiting for deposit... new Thread(){
going to deposit... public void run(){c.deposit(12000);}
Deposit of 12000 completed... }.start(); } }
Withdraw of 500 completed...
Questions?
• 5 states in Thread model?
• Two ways to Create threads ?
• Methods in Thread priorities?
• Use of Synchronization?
• What is Inter-thread communication?
Summary
Thread model,
Creating threads
Thread priorities
Synchronization
Inter-thread communication
Queries???
END OF UNIT - 06
Deadlock and Semaphore
//For your reference
Semaphores can be used to restrict the number of threads that access a
shared resource.
Deadlocks can be avoided by using a proper resource ordering
Creating and Executing threads
with the Executor Framework
//For your reference
• Server Programs such as database and web servers repeatedly
execute requests from multiple clients and these are oriented around
processing a large number of short tasks.
• In server application, it creates a new thread each time a request
arrives and service this new request in the newly created thread.
• Disadvantage: A server that creates a new thread for every request
would spend more time and consume more system resources in
creating and destroying threads than processing actual requests.
Creating and Executing threads
with the Executor Framework
//For your reference
• As active threads consume system resources, a JVM creating too
many threads at the same time can cause the system to run out of
memory.
• This necessitates the need to limit the number of threads being
created.
• Solution: ThreadPool
• A thread pool reuses previously created threads to execute current
tasks and offers a solution to the problem of thread cycle overhead
and resource thrashing.
• Since the thread is already existing when the request arrives, the
delay introduced by thread creation is eliminated, making the
application more responsive.
Creating and Executing threads
with the Executor Framework
//For your reference
• Java provides the Executor framework which is centered around the
• Executorinterface, its sub-interface–ExecutorService and the class
ThreadPoolExecutor, which implements both of these interfaces.
• By using the executor, one only has to implement the Runnable
objects and send them to the executor to execute.
• To use thread pools, we first create a object of Executor Service and
pass a set of tasks to it. ThreadPoolExecutor class allows to set the
core and maximum pool size. The runnables that are run by a
particular thread are executed sequentially.
Creating and Executing threads
with the Executor Framework
//For your reference
Some types of Java Executors are listed below:
1. SingleThreadExecutor – For sequential execution
2. FixedThreadPool(n)+ - Fixed no. of threads
3. CachedThreadPool – reuse previously constructed
4. ScheduledExecutor – to run at regular interval
Syntax: ExecutorService executor = Executors.new SingleThreadExecutor();
Creating and Executing threads
with the Executor Framework
//For your reference
• One of the main advantages of using this approach is when you want
to process 100 requests at a time, but do not want to create 100
Threads for the same, so as to reduce JVM overload.
• You can use this approach to create a ThreadPool of 10 Threads and
you can submit 100 requests to this ThreadPool. ThreadPool will
create maximum of 10 threads to process 10 requests at a time.
• After process completion of any single Thread, ThreadPool will
internally allocate the 11th request to this Thread and will keep on
doing the same to all the remaining requests.