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

Multi-Threaded Programming: CS F213: Object Oriented Programming

The document discusses multi-threaded programming in Java. It covers key concepts like threads, states of threads, thread priority, context switching, synchronization, monitors, messaging between threads, and classical problems like producer-consumer. Examples of creating and running threads using the Runnable interface and Thread class are also presented.

Uploaded by

umanggoel123456
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 views30 pages

Multi-Threaded Programming: CS F213: Object Oriented Programming

The document discusses multi-threaded programming in Java. It covers key concepts like threads, states of threads, thread priority, context switching, synchronization, monitors, messaging between threads, and classical problems like producer-consumer. Examples of creating and running threads using the Runnable interface and Thread class are also presented.

Uploaded by

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

Multi-threaded Programming

CS F213: Object Oriented Programming

Dipanjan Chakraborty
Department of CS&IS

1
Threads in Java

A multithreaded program has two or more paths that can
run concurrently
– Each such part is called a thread

Each thread defines a separate path of execution

Recall: threads in the context of Operating Systems

e.g. on Android smartphones, the GUI part of the app runs
on a separate thread from the backend / logic part

2
Threads in Java

Multithreading allows better efficiency by keeping idle
time to the minimum

Important for interactive systems and networked
programs

In single threaded programs, the program would block on
long running tasks
– e.g. network read or long computation

3
Threads in Java

Single processor / single core systems: threads
are concurrent. Idle time may be used by other
threads

Multi processor / multi core systems: threads
can run in parallel

4
States of a Thread

Running

Ready to run

Suspended

Resumed

Blocked

Terminated

5
Thread Priority

Thread priority numbers determine relative
priority of the threads

Does not have to do anything with processing
speed / power. Rather, is an indicator of the
priority given to a thread when multiple
threads are competing for processing time

6
Context Switching

The process of switching from one running
thread to another

Threads can voluntarily relinquish control

Threads can be pre-empted by higher priority
threads

7
Synchronisation

Why is synchronisation required?
– e.g. Two threads working on a common data
structures should not make conflicting changes
– One thread should not be writing the data
while another thread is reading it

Java uses monitor to achieve synchronisation

8
Monitor

A monitor is like a box which only one thread can enter at a
time. All other threads must wait when one thread is in the
monitor

Each object in Java has its own implicit monitor that is
automatically entered when one of the object’s synchronized
methods is called

Once a thread is inside a synchronized method, no other
thread can call any other synchronized method on the same
object

More later

9
Messaging

Java provides a clean, low-cost way for two or more
threads to talk to each other, via calls to predefined
methods that all objects have

Java’s messaging system allows a thread to enter a
synchronized method on an object, and then wait there
until some other thread explicitly notifies it to come out

More later

10
The main thread

When a Java program starts up, one thread begins
running immediately: the main thread

It is the thread from which other “child” threads
will be spawned

Often, it must be the last thread to finish
execution because it performs various shutdown
actions

11
The main thread

Reference to the current thread can be
obtained by the public static method
Thread.currentThread()

Let’s look at an example

12
Creating a Thread
● Implement the Runnable interface
● Extend the Thread class

13
Implementing Runnable

A new class implements the Runnable interface and has an Thread object
as a member

Need to implement the method run()

run( ) establishes the entry point for another, concurrent thread of
execution within the program

The new thread will end when run( ) returns

In the main thread, the start() method called on the thread member creates
a new thread.

The execution of the new thread begins in the run() method in the thread

Let’s look at an example

14
Extending the Thread class

A new class extends the Thread class

Need to implement the method run()

run( ) establishes the entry point for another, concurrent thread of execution within the
program

The new thread will end when run( ) returns

In the main thread, the start() method called on an object of the new class, creates a new
thread.

The execution of the new thread begins in the run() method in the thread

Let’s look at an example

15
Which approach should be chosen?

Some java programmers feel classes should be
extended only when they are enhanced. So
implementing Runnable is the right way to
create Threads

Implementing Runnable allows the thread to
inherit (extend) other classes

16
Know if a thread has ended

Call method final boolean isAlive() on a thread
– Returns true if the thread is still running and false
otherwise

final void join( ) throws InterruptedException
– Waits until the thread on which join() is called has
terminated

Modify the previous programs using join() in the main
thread

17
Thread Priority

Call the setPriority() and getPriority() methods
on a thread

Priority needs to be within two constants:
MIN_PRIORITY and MAX_PRIORITY (1 and 10)

Default priority is NORM_PRIORITY (5)

The constants are static final variables in Thread
18
Synchronisation

A method can be qualified with the synchronized
keyword

When a synchronized method on an object is called in a
thread, any other thread calling the method on the same
object will be suspended until the first thread exits the
monitor
– A thread is said to have entered the monitor when it
acquires a mutually exclusive lock

19
Synchronized statement

Often one would use third party code but desire synchronised operations

Or, a certain class was not designed with multi-threading in focus

A group of statements may be enclosed in a synchronised block to achive this
synchronized(objRef) {
// statements to be synchronized

}

Synchronized(this) can be used to make a part of a method
synchronized

20
Inter-thread Communication

How would a thread become aware that an event
has happened?
– Polling: loop until a condition is true
– Wastes CPU cycles

Java provides mechanisms for inter-thread
communication which overcomes the need for
polling

21
Inter-thread Communication

wait(), notify(), notifyAll() methods are final
methods in the Object class
– Can be called only from within a synchronized context

wait( ) tells the calling thread to give up the monitor and go to
sleep until some other thread enters the same monitor and calls
notify( ) or notifyAll( )

notify( ) wakes up a thread that called wait( ) on the same object

notifyAll( ) wakes up all the threads that called wait( ) on the
same object. One of the threads will be granted access
22
Classical Producer-Consumer Problem

Consider a Queue, Q, of finite-size

Consider a Producer, P, which is populating Q with
new ‘items’

P can’t produce when Q is full

Consider a Consumer, C, which is consuming ‘items’
from Q

Q can’t consume when Q is empty

P and C should not be working on the same cell in Q

What should be synchronized?
23
Spurious Wake-ups

Sometimes threads may wake-up without a
notify() or notifyAll() call
– This is because how POSIX threads behave:
threads resume on receiving any signal
– Java threads might be using POSIX threads

Solution: test for an invariant
24
Deadlocks

Two threads might have a circular dependency

The program(s) need to be aborted to get out
of the deadlock
1 class X { 1 class Y {
2 synchronized mX() { 2 synchronized mY() {
3 mY(); 3 mX();
4 } 4 }
5 } 5 }

Thread 1 enters Thread 2 enters


25
Suspending, Resuming and Stopping
Threads

The suspend(), resume() and stop() methods
have been deprecated as they could lead to
deadlocks and inconsistent system states

Instead, if required, the wait() and notify()
methods are used along with a boolean flag to
control suspensions / resumptions only at
certain points in the code
26
Suspending, Resuming and Stopping
Threads
1 synchronized void mysuspend() {
1 boolean suspendFlag = false; 2 suspendFlag = true;
2 public void run() { 3 }
3 try {
4 synchronized(this) {
5 while(suspendFlag) {
6 wait();
7 }
8 } 1 synchronized void myresume() {
9 } catch (...) {} 2 suspendFlag = false;
10 } 3 notify();
4 }

27
Obtaining the state of a Thread

Thread.State getState( )

28
Factory Methods

A factory method is a method that returns an
object of a class. Typically, factory methods are
static methods of a class.

They are used for a variety of reasons, such as
to set an object to some initial state prior to
use, to configure a specific type of object, or in
some cases to enable an object to be reused.
29
Factory Methods for Java Threads

Can be used to create and start the thread
through one method call

1 public static NewThread createAndStart() {


2 NewThread myThrd = new NewThread();
3 myThrd.t.start();
4 return myThrd;
5 }

1 NewThread nt = NewThread.createAndStart();
30

You might also like