MultiThreading

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

1

Chapter 11
Multithreading

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
2

Thread
• Thread: single sequential flow of control within a
program
• Single-threaded program can handle one task at
any time.
• Multithreading allows two or more parts that
can run concurrently.
• Multithreading is specialized form of
multitasking.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
3

Multitasking
• Multitasking is the ability of a computer's
operating system to run several programs (or
processes) concurrently on a single CPU.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
4

Multitasking
• Process based multitasking (heavyweight tasks)

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
5

Multitasking
• Thread based multitasking(Lightweight tasks)

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
6

Advantages of Multithreading

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
7

Threads Concept
Multiple
threads on
multiple
CPUs

Multiple
threads
sharing a
single CPU

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
8

Thread States

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
9

Thread Life cycle


• 1. New: Thread is in new state, when an instance of thread class is
created and before calling start( ) method.
• 2. Runnable: A thread is in runnable state after invocation of
start() method, but the thread scheduler has not selected it to be the
running thread.
• 3. Running: The thread is in running state if the thread scheduler
has selected it.
• 4. Non-Runnable (Blocked): This is the state when the thread is
still alive, but is currently not eligible to run.
• 5. Terminated: A thread is in terminated or dead state when its
run() method exits.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
10

Thread Priorities
Java Assigns priority to each thread. Thread priorities are integers.

•MIN_PRIORITY (a constant of 1)
•MAX_PRIORITY (a constant of 10).
•NORM_PRIORITY (a constant of 5, default).

Priorities are used to determine when to switch from one thread to


another thread called context switching. Rules for context switching:

•A thread can voluntarily relinquish control


•A thread can be pre-empted by a higher – priority thread.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
11

Threads in Java
Creating threads in Java:

• Extend java.lang.Thread class


OR
• Implement java.lang.Runnable interface

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
12

Extending Thread
Follow below steps to create thread by extending
Thread class,
1. Extend Sub class by Thread class
2. Override run( ) method of Thread class inside sub
class
3. Create sub-class object in main() in another class
4. Call start( ) method by sub-class object

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
13

Example
class thrExample extends Thread
{
public void run()
{
System.out.println("---- Execution by Child Thread ----");
}
}
public class Demo
{
public static void main(String [] args)
{
thrExample t1 = new thrExample();
thrExample t2 = new thrExample();
t1.start();
t2.start();
}
}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
14

Example

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
15

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
16

Methods

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
17

Example – 2(Different methods of thread)


class thrExample extends Thread
{
thrExample(String thName){
super(thName);
}
public void run()
{
System.out.println("---- New Thread ----");
System.out.println("Current Thread : "
+getName());
System.out.println("Thread Priority: "
+getPriority());
System.out.println("Thread Status : " +isAlive());
System.out.println("Thread Id : " +getId());
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
} rights reserved. 0136012671
18

public class Demo


{
public static void main(String [] args){
thrExample t1 = new thrExample("ONE");
thrExample t2 = new thrExample("TWO");
System.out.println("Current Thread : "
+Thread.currentThread());
t1.start();
t2.start();
}
} Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
19

Implementing Runnable Interface


Follow below steps to create thread by implementing
Runnable Interface
1. Create sub class by implementing Runnable
interface
2. Override run( ) method inside the subclass
3. Create Thread object by calling Thread constructor
and pass object of sub class as parameter
4. Call start( ) method by Thread object

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
20

Example
class threadRun implements Runnable {
public void run() {
System.out.println("Thread is executing using runnable
interface");
}
}
Class Demo {
public static void main(String[] args) {
threadRun tr = new threadRun();
Thread t = new Thread(tr);
Thread t1 = new Thread(tr);
Thread t2 = new Thread(tr);
t.start();
t1.start();
t2.start();
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
} rights reserved. 0136012671
21

Creating Multiple Threads

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
22

Creating Multiple Threads

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
23

Main Thread

• When Java program starts execution, one thread


begins immediately, that thread is termed as
main thread.
• Main thread is required for two reasons, namely
▫ This thread spawns child threads
▫ Performs various shutdown activities before
completing execution.
• Main thread is a last thread to complete
execution.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
24

Synchronization
• When two or more threads needs to access shared data, then
data inconsistency problem arises. Imagine a scenario,
▫ Thread T1 is writing data into a file numbers.txt.
▫ Thread T2 is reading data from a file numbers.txt.
• In this scenario, when T1 is writing, if T2 reads the file
concurrently, data may not be correct. Hence, when one
thread is using shared resource, other threads should not be
allowed to use until first thread completes the task.
• In Java, synchronization is achieved using monitor or lock.
• Each object has unique lock associated with them.
• A thread that needs to access shared resource, first acquires
the lock, as soon as completes the execution, thread
automatically releases the lock.
• To synchronize the function, prefix the keyword
synchronized in function definition
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
25

Synchronized Blocks

synchronized(Object){
//Statements to be synchronized
}

Where, Object -> is a reference to the object being referenced.

Refer Notepad: Example without synchronization & example


with synchronization

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
26

Synchronized Blocks

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
27

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
28

Inter Thread Communication


• It is mechanism that allows two or more synchronized threads to
communicate with each other.
• In Java, Inter thread communication is achieved using
o wait( )
o notify( )
o notifyAll( )

wait( )
• The wait method releases the lock of current thread and moves it to waiting
state. Thread will awake, when other thread calls notify( ) or notifyAll( )
method for the object, or till specified time elapses.

Prototype:

1. public final void wait( ) throws InterruptedException


2. public final void wait(long timeout) throws InterruptedException

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
29

notify( )
•Notifies the thread in waiting state on the same object to wake up.
Prototype:
1. public final void notify( )

notifyAll( )
•Notifies all threads in waiting state on the same object to wake up.
Prototype:
1. public final void notifyAll( )

Process of Inter Thread Communication:

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
30

Working of threads with respect to diagram


• Threads enter to acquire lock.

• Lock is acquired by on thread.

• Now thread goes to waiting state if you call wait() method on the
object. Otherwise it releases the lock and exits.

• If you call notify() or notifyAll() method, thread moves to the


notified state (runnable state).

• Now thread is available to acquire lock.

• After completion of the task, thread releases the lock and exits the
monitor state of the object.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
31

Difference between wait( ) and


sleep( )

• Refer notepad for ITC_customer example

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
32

Producer – Consumer Problem


• In this problem we have two processes, producer and consumer, who share
a fixed size buffer. Producer work is to produce data or items and put in
buffer. Consumer work is to remove data from buffer and consume it. We
have to make sure that producer do not produce data when buffer is full and
consumer do not remove data when buffer is empty.

• The producer should go to sleep when buffer is full. Next time when
consumer removes data it notifies the producer and producer starts
producing data again. The consumer should go to sleep when buffer is
empty. Next time when producer add data it notifies the consumer and
consumer starts consuming data. This solution can be achieved using
semaphores.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
33

Bounded Buffer Problem


In computing, the producer–consumer problem is a classic example of a
multi-process synchronization problem. The problem describes two processes,
the producer and the consumer, which 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.
Problem
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.

Solution
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.
•Refer notepad for example
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
34

Refer notepad for bounded buffer example

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671

You might also like