Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 44

1

Multithreading / Concurrency

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

Thread
• A thread is a lightweight subprocess, the
smallest unit of processing.
• It is a separate path of execution
• Threads are independent.
• If there occurs exception in one thread, it doesn't
affect other threads.
• It uses a shared memory area.

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

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

Life Cycle of a Thread

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

Life Cycle of a Thread


• New − A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as
a born thread.
• Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while
the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state
for a specified interval of time. A thread in this state transitions back
to the runnable state when that time interval expires or when the
event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state
when it completes its task or otherwise terminates.

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

Thread Priorities
• Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
• Java thread priorities are in the range between MIN_PRIORITY (a
constant of 1) and MAX_PRIORITY (a constant of 10).
• By default, every thread is given priority NORM_PRIORITY (a constant
of 5).
• Threads with higher priority are more important to a program and should
be allocated processor time before lower-priority threads.
• However, thread priorities cannot guarantee the order in which threads
execute and are very much platform dependent.

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

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

Multithreading
• Thread: single sequential flow of control within a
program
• Single-threaded program can handle one task at
any time.
• Multitasking allows single processor to run
several concurrent threads.
• Most modern operating systems support
multitasking.

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

Advantages of Multithreading
• Reactive systems – constantly monitoring
• More responsive to user input – GUI application
can interrupt a time-consuming task
• Server can handle multiple clients
simultaneously
• Can take advantage of parallel processing

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

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
11

Threads in Java
Creating threads in Java:
• Extend java.lang.Thread class
▫ run() method must be overridden (similar to main
method of sequential program)
▫ run() is called when execution of the thread begins
▫ A thread terminates when run() returns
▫ start() method invokes run()
▫ Calling run() does not create a new thread
• Implement java.lang.Runnable interface
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
12

Thread class:
«interface»
java.lang.Runnable

java.lang.Thread
+Thread() Creates a default thread.
+Thread(task: Runnable) Creates a thread for a specified task.
+start(): void Starts the thread that causes the run() method to be invoked by the JVM.
+isAlive(): boolean Tests whether the thread is currently running.
+setPriority(p: int): void Sets priority p (ranging from 1 to 10) for this thread.
+join(): void Waits for this thread to finish.
+sleep(millis: long): void Puts the runnable object to sleep for a specified time in milliseconds.
+yield(): void Causes this thread to temporarily pause and allow other threads to execute.
+interrupt(): void Interrupts this thread.

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

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

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

Thread termination
A thread becomes Not Runnable when one of
these events occurs:

• Its sleep method is invoked.


• The thread calls the wait method to wait for a
specific condition to be satisifed.
• The thread is blocking on I/O.

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

Runnable interface:
• The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
• Runnable interface have only one method named run().public
void run(): is used to perform action for a thread.
• Starting a thread:
• start() method of Thread class is used to start a newly created
thread. It performs following tasks:A new thread starts(with new
callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method
will run.

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

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

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

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

Thread Scheduler in Java

• Thread scheduler in java is the part of the


JVM that decides which thread should run.
• There is no guarantee that which runnable
thread will be chosen to run by the thread
scheduler.
• Only one thread at a time can run in a single
process.
• The thread scheduler mainly uses preemptive or
time slicing scheduling to schedule the threads
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Two ways:Creating Threads
1. Implement the Runnable Interface.
2.Extend the Thread class.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
First Approach-Implement Runnable
Create a class that will implement Runnable.
To implement Runnable, the class need only to
implement :
public void run()
-Establishes the entry point for another,
concurrent thread.
Introduce an object of type Thread from within
the same class.
Call the start() method of the new object of
type Thread.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example-First Approach
class NewThread implements Runnable class threadDemo
{ {
Thread t; public static void main(String args[])
NewThread() {
{ new NewThread();
t = new Thread(this, "demo thread"); try
System.out.println("Child thread: " +t); {
t.start(); for(int n=5;n>0;n--)
} {
System.out.println("Main Thread: " +n);
Thread(Runnable thob, String
public void run() Thread.sleep(1000);
{
thname)
try }
}
{ catch(InterruptedException e)
for(int n=5;n>0;n--) {
{ System.out.println("Main Interrupted.");
System.out.println("Child Thread: " +n); }
Thread.sleep(500);
} System.out.println("Exiting Main thread.");
}
catch(InterruptedException e) }
{ }
System.out.println("Child Interrupted.");
}
System.out.println("Exiting child thread.");
}

} Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Output
Child thread: Thread[demo thread, 5, main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting Child Thread
Main Thread: 2
Main Thread: 1
Exiting Main thread

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Second Approach- Extends Thread
Create a new class that extends Thread and then create
an instance of that class.
The extending class must override the run() method.
It must also call the start() method to begin execution of
the new thread.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example-Second Approach
class exthread
class NewThread extends Thread {
{ public static void main(String args[])
NewThread() {
{ new NewThread();
super("demo thread");
System.out.println("Child Thread: "+this); try{
start(); for(int i=5;i>0;i--)
} {
System.out.println("Main Thread: "+i);
public void run() Thread.sleep(1000);
{ }
try{ }
for(int i=5;i>0;i--) catch(InterruptedException e)
{ {
System.out.println("Child Thread: "+i); System.out.println("Main Interrupted.");
Thread.sleep(500); }
}
} System.out.println("Exiting Main Thread.");
catch(InterruptedException e) }
{ }
System.out.println("Child Interrupted.");
}
System.out.println("Exiting Child Thread.");
}
}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Creating Multiple Thread
class NewThread implements Runnable class multhread
{ {
String name; public static void main(String args[])
Thread t; {
new NewThread("One");
NewThread(String tmp) new NewThread("Two");
{ new NewThread("Three");
name=tmp;
t= new Thread(this,name); try
System.out.println("New Thread: "+t); {
t.start(); Thread.sleep(10000);
} }
public void run() catch(InterruptedException e)
{ {
try System.out.println("Main Interrupted.");
{ }
for(int i=5;i>0;i--) System.out.println("Exiting Main.");
{ }
System.out.println(name+" : "+i); }
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+" Interrupted.");
}
System.out.println(name + " Exiting.");
}
}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Output
New thread: Thread [One, 5, main]
New thread: Thread [Two, 5, main]
New thread: Thread [Three, 5, main]
One: 5
Two: 5
Three:5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One Exiting
Two Exiting
Three Exiting
Main Exiting

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
New thread: Thread [One, 5, main] One: 1
Output
New thread: Thread [Two, 5, main]
New thread: Thread [Three, 5, main]
Three: 1
Two: 1
One alive: true One Exiting
Two alive: true Two Exiting
Three alive: true Three Exiting
Main is Waiting. One alive: false
One: 5 Two alive: false
Two: 5 Three alive: false
Three:5 Main Exiting
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2

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

The Static yield() Method


You can use the yield() method to temporarily release
time for other threads.

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

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

Sleep method in java

• The sleep() method of Thread class is used to


sleep a thread for the specified amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for
sleeping a thread:
public static void sleep(long miliseconds)throws
InterruptedException

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

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

The join() Method


The join() method waits for a thread to die. In other words, it
causes the currently running threads to stop executing until the
thread it joins with completes its task.

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

Example of join() method

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

Example of join(long miliseconds) method

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

Thread methods
isAlive()
• method used to find out the state of a thread.
• returns true: thread is in the Ready, Blocked, or
Running state
• returns false: thread is new and has not started or if it is
finished.
interrupt()
•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 an
java.io.InterruptedException is thrown.

•The isInterrupt() method tests whether the thread is


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

Thread Synchronization

A shared resource may be corrupted if it is


accessed simultaneously by multiple threads.
Example: two unsynchronized threads accessing
the same bank account may cause conflict.
Step balance thread[i] thread[j]

1 0 newBalance = bank.getBalance() + 1;
2 0 newBalance = bank.getBalance() + 1;
3 1 bank.setBalance(newBalance);
4 1 bank.setBalance(newBalance);

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
39
synchronized
• Synchronization in java is the capability to control the access of
multiple threads to any shared resource.
• Java Synchronization is better option where we want to allow only
one thread to access the shared resource.
• Why use Synchronization
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
• Types of Synchronization
• There are two types of synchronization
Process Synchronization
Thread Synchronization

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

Thread Synchronization

• There are two types of thread synchronization


mutual exclusive and inter-thread
communication.
• Mutual Exclusive
▫ Synchronized method.
▫ Synchronized block.
▫ static synchronization.
• Cooperation (Inter-thread communication in
java)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
41

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

Java synchronized method

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

Synchronized block in java

• Synchronized block can be used to perform


synchronization on any specific resource of the
method.
• Suppose you have 50 lines of code in your method,
but you want to synchronize only 5 lines, you can use
synchronized block.
• If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.

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

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

You might also like