Multithreading

CSC 480
Software Engineering
Multithreading
What Is a Thread?


A thread is a sequential flow of control within a
single program
Thread vs. Process
 A process
is allocated resources such as an address
space, memory, file, etc. It defines an execution
environment for a thread
 Multiple threads may share the resources. Each of
them has its own context (including execution stack,
program counter, etc )
How Does It Work? w/ One Processor


The operating system switch back and forth
between multiple processes, giving the illusion
that they run in parallel
The Java language provides a comprehensive
solution that breaks the borders between
programming language, supporting libraries, and
system APIs.
 Handles
time-slicing among threads seemingly
running in parallel
When to Use Threads?

Sometimes you may want to split the control flow
of your program such that you can
 Execute
IO and some process-heavy tasks in
separate threads
 Process requests from two or more clients
simultaneously
 Divide workload among several concurrent threads to
improve performance
How to Define a Thread?

There are two techniques to choose from
the java.lang.Thread class
 Implementing the java.lang.Runnable interface
 Subclassing


You have to use it if your class is a subclass of another class
in your application
Both require defining a run method
public void run()
Define the logic that needs to be carried out in
that thread
Sample Code – defining the thread
public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {
}
}
System.out.println("DONE! " + getName());
}
}
Sample Code – starting the thread
public class TwoThreadsDemo {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
Click here to see the sample result.
http://java.sun.com/docs/books/tutorial/essential/threads/simple.html
Use the following example to see competing threads
printing scrambled messages: RepeatedMessage.java under
M:\Martin Zhao\CSC480\fall 2004\workshops\Workshop 4\examples\threads
The Life Cycle of a Thread

Each thread has
 thread
state
sleep/wait/IO
 priority

Thread states:
 new
(before start called)
 runnable
 blocked
 dead (after run method exits)
Expires/notify/IO
Scheduling Threads

Scheduler activates new thread if
a
thread has completed its time slice
 a thread has blocked itself
 a thread with higher priority has become runnable

Scheduler determines new thread to run
 looks
only at runnable threads
 picks one with max priority
Thread Synchronization

When threads share access to a common
object, they conflict with each other
 Two
threads in a banking application trying to access
one account: one to deposit and one to withdraw

Object lock
 The
code segments within a program that access the
same object from separate, concurrent threads are
called critical sections
 The thread with the object can access a critical
section at any given time
Visualizing Locks




Object = phone booth
Thread = person
Locked object = closed booth
Blocked thread = person
waiting for booth to open
Two Ways to protect a critical section


Synchronized method
Synchronized block
public static synchronized
void displayMessage( RepeatedMessage rm )
throws InterruptedException {
//synchronized ( sharedLock) {
for( int i=0; i < rm.message.length(); i++ ) {
System.out.print( rm.message.charAt( i ) );
Thread.currentThread().sleep( 50 );
}
System.out.println();
//}
}
Communication Btw Threads


Each object has lock
Three methods in the Object class can facilitate
the interthread communication
 wait:
a method of a thread object that holds the lock
can choose to wait until certain condition changes
 notify: wakes up a single thread that is blocked by
invoking the wait method
 notifyAll : wakes up all threads that are blocked
by invoking the wait method