Professional Documents
Culture Documents
Final Thread
Final Thread
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
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
5
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:
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:
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
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
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
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
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
35
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
36
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.
Thread Synchronization
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
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
42
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
43
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671