Chapter 7
Chapter 7
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
What is Multithreading?
A single threaded program
begin
class ABC
{
…
public void main(..) body
{
…
…
}
}
end
A multithreaded program
Main thread
{...};
sort() calculate() search()
. calculate() calculate()
{...};
. search()
{...}; search()
. print()
{...}; print() print()
}
The concept
Single task →
Two tasks →
Multiprocessing (multi-threading)
• Multiple processing units (multiprocessor).
• Computer works on several tasks in parallel.
• Performance can be improved.
Thread
Example
Example
Web/ Internet applications
PC client
Internet
Server
PDA
Serving many users simultaneously
Multithreaded server
Server
Threads
Internet
Client 2 Process
Printing
thread
Editing
thread
Inactive Dead
terminates
Start() run()
Alive
Runnable is interface
• So it can be multiply inherited
• Required for multithreading in applets
Running a thread in Java
Creating Threads with Threa
Creating threads in Java
There are two ways to create and run a thread:
Thread class
public class Thread extends Object { …
}
Runnable interface
{
public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("From Thread
public void run( ) {
for(int j = 1; j <= 5; j++) { A with i = "+ -1*i);
System.out.println("Exiting from Thread C ...");
}
System.out.println("From Thread B with j = "+2* j);
}
}
System.out.println("Exiting from Thread B ..."); }
System.out.println("Exiting
} from Thread A ...");
} class MultiThreadClass
{
class ThreadC extends Thread
} {
}
System.out.println("... Multithreading is over ");
}
}
OBJECT ORIENTED PROGRAMMING WITH JAVA
Multithreaded Programming in Java – II
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Creating Threads with Runnable
Creating thread in Java
2. Runnable interface
Create object implementing Runnable interface
Pass it to Thread object via Thread constructor
Example
}
System.out.println("Thread Y with j = "+ 2*j);
}
}}
System.out.println("Exiting Thread
}
System.out.println("Exiting Thread Y ..."); X ...");
} class MultiThreadRunnable {
} public static void main(String args[]) {
class ThreadZ implements Runnable
class ThreadY implements Runnable { ThreadX x = new ThreadX(); {
public void run( ) {
public void run( ) { Thread t1 = new Thread(x); for(int k = 1; k <= 5; k++) {
System.out.println("Thread Z with k = "+ 2*k-1);
for(int j = 1; j <= 5; j++) { ThreadY y = new ThreadY(); }
System.out.println("Exiting Thread Z ...");
Threadj t2
System.out.println("Thread Y with = new
= "+ Thread(y);
2*j); }
}
} }
States of a Thread
Threads : Thread states of a thread
Java thread can be in one of these states :
New – thread allocated & waiting for start()
Runnable – thread can begin execution
Running – thread currently executing
Blocked – thread waiting for event (I/O, etc.)
Dead – thread finished
Transitions between states caused by
Invoking methods in class Thread
new(), start(), yield(), sleep(), wait(), notify()…
Other (external) events
Scheduler, I/O, returning from run()…
Thread States
State diagram
new start notify, notifyAll,
new runnable IO complete,
sleep expired,
yield, join complete
scheduler time resume
slice
running blocked
IO, sleep,
terminate wait, join,
suspend
dead
Thread control methods
start () :→ A newborn thread with this method enter into Runnable state and Java run time create a system thread
context and starts it running. This method for a thread object can be called once only
suspend() :→ This method is different from stop( ) method. It takes the thread and causes it to stop running and later on
can be restored (by resume() )
resume() :→ This method is used to revive a suspended thread. There is no gurantee that the thread will start running
right way, since there might be a higher priority thread running already, but, resume() causes the thread to
become eligible for running
sleep(int n):→ This method causes the run time to put the current thread to sleep for n milliseconds
yield() :→ This method causes the run time to switch the context from the current thread to the next available runnable
thread. This is one way to ensure that the threads at lower priority do not get started
Scheduling of Threads
Daemon threads
Java threads types
User
Daemon
− Provide general services.
− Typically never terminate.
− Call setDaemon() before start().
Program termination
All user threads finish.
Daemon threads are terminated by JVM.
Main program finishes.
Threads : Scheduling
Scheduler
Determines which runnable threads to run.
Can be based on thread priority.
Part of OS or Java Virtual Machine (JVM) .
Scheduling policy
Nonpreemptive (cooperative) scheduling.
Preemptive scheduling.
Threads: Non-preemptive scheduling
Threads continue execution until
Thread terminates.
Executes instruction causing wait (e.g., IO).
Thread volunteering to stop (invoking yield or sleep).
Threads: Preemptive scheduling
Threads continue execution until
Same reasons as non-preemptive scheduling.
Preempted by scheduler.
Java thread : An example
public class ThreadExample extends Thread {
public void run() {
for (int i = 0; i < 3; i++) {
try {
sleep ((int)(Math.random() * 5000)); // 5 secs
}
catch (InterruptedException e) {
System.out.println (i);
}
}
public static void main(String[ ] args) {
new ThreadExample().start();
new ThreadExample().start();
System.out.println ("Done");
}
}
Java Thread Example
Possible outputs
0,1,2,0,1,2,Done // thread 1, thread 2, main()
0,1,2,Done,0,1,2 // thread 1, main(), thread 2
Done,0,1,2,0,1,2 // main(), thread 1, thread 2
0,0,1,1,2,Done,2 // main() & threads interleaved
Data races
public class DataRace extends Thread {
static int x;
public void run() {
for (int i = 0; i < 100000; i++) {
x = x + 1;
x = x – 1;
}
}
public static void main(String[] args) {
x = 0;
for (int i = 0; i < 100000; i++)
new DataRace().start();
System.out.println(x); // x not always 0!
}
}
Thread scheduling observations
C extends
extends Thread
}
class
}
class A
B Thread
{{
public
public void
void run()
run()
{{
System.out.println ("Thread
System.out.println ("Thread AC started");
B started");
for (int
for (int j=1;j<=4;j++)
i=1;i<=4;i++)
k=1;k<=4;k++)
{{
System.out.println ("\t
System.out.println ("\t From
From ThreadA:
ThreadC: i=
ThreadB: k= "+i);
j= "+k);
"+j);
}}
System.out.println ("Exit
System.out.println ("Exit from
from A");
C");
B");
}}
}
}
Thread priority : An example
class ThreadPriority
{
public static void main (String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority (Thread.MAX_PRIORITY);
threadB.setPriority (threadA.getPriority()+1);
threadA.setPriority (Thread.MIN_PRIORITY);
System.out.println ("Started Thread A");
threadA.start();
System.out.println ("Started Thread B");
threadB.start();
System.out.println ("Started Thread C");
threadC.start();
System.out.println ("End of main thread");
}
}
Thread class : Join
Short form: