Download CS220 Software Development

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS220 Software Development
Lecture: Multi-threading
A. O’Riordan, 2009
Threads
• So far, everything we have done has involved a single sequence of
events (although a GUI and the garbage collector may be doing
other things)
• when we invoked a method at line X in our code, Java goes off and
executes that method, and only once it is finished does it return
control to X+1, and continues from there.
• but Java also allows us to set off separate threads of execution,
called threads, which run concurrently …we call this multi-threading
• Threads are a way for a program to fork (or split) itself into two or
more simultaneously (or pseudo-simultaneously) running tasks
Features of Multi-threading
• Reactive programming – do more than one thing as a reactive
response to some input – e.g. GUIs
• Controllability – ability to suspend, resume, and stop threads
• Asynchronous Messages – avoid waiting for unrelated actions to
complete
– Perform blocking I/O without blocking the entire program
• Parallelism – on machines with multiple processors can improve on
performance
Support in Java
• Multithreading support in Java from beginning – based on Simula
and Mesa
– Java 5 incorporated many additions and clarifications to the Java
concurrency model
• “Built-in support for threads provides Java programmers with a
powerful tool to improve interactive performance of graphical
applications.” Java Language Environment White Paper, Gosling and McGilton
• The term thread-safe means that a given library function is
implemented in such a manner that it can be executed by multiple
concurrent threads of execution
Thread states
•A new thread begins in the new state
•It transitions to the runnable state when the program starts the
thread
•A thread transitions to the waiting state while another thread
performs a task
•A runnable thread can transition to a timed waiting state for a
specified interval of time
Concurrent Execution
• Each thread in the runnable state runs for a short period of time and
then the computer system switches to another thread (it is
dispatched)
• The operating system’s thread scheduler determines which thread
runs next
• Normally each thread is given a small amount of time called a timeslice or a quantum
• This gives the illusion that the threads are running in parallel
• Actually threads may run in parallel on multi-processor or multi-core
systems
Threads
• Two ways to run a thread: (i) Subclass Thread; (ii) Implement
Runnable interface (preferable)
• Java supplies a class Thread, which allows us to start a separate
thread of execution
• A Thread object has a run() method, which tells the system what
to do during this thread
• To start a thread, use the start() method, which then invokes the
run() method
• By default, run() does nothing – you must override it to do what
you want.
Ping pong example
public class Pinger extends Thread {
public void run() {
for (int i = 0; i<100; i++)
System.out.print("ping ...");
}
}
public class Ponger extends Thread {
public void run() {
for (int i = 0; i<100; i++)
System.out.print("... pong");
}
}
Playing Ping Pong
public class PingPong
public static void
Pinger pinger =
Ponger ponger =
{
main(String[] args);
new Pinger();
new Ponger();
pinger.start();
ponger.start();
}
}
start() starts its thread,
then immediately hands
back control, so that the
second thread can begin.
Both threads run concurrently.
Threads using interfaces
Instead of directly subclassing Thread, we can implement the
Runnable interface, by specifying the run() method
1.
2.
3.
4.
5.
Create class implementing Runnable
Specify run() method
Create object of class
Construct a Thread object from Runnable object
Call the start() method of Thread
Advantages of this approach
• Can use thread pools (see later)
• Inheritance is still available to your class
Runnable
• Runnable interface is very simple. The class must define a method
of no arguments called run.
public interface Runnable {
public abstract void run() {
}
class Mine implements Runnable {
public void run() {
//code here
}
Ping Pong using Runnable
public class Pinger implements Runnable {
public void run() {
for (int i = 0; i<100; i++)
System.out.println("ping ...");
}
}
public class PingPong
public static void
Thread t1 = new
Thread t2 = new
t1.start();
t2.start();
}
}
{
main(String[] args) {
Thread(new Pinger());
Thread(new Ponger());
Remarks
• each call to start() begins a new thread
• a call to run() does not begin a new thread – it just begins the
computation in the existing thread
• the two threads in PingPong are almost identical, so they operate
more or less in step with each other ...
– ... but not necessarily – actual behaviour depends on the
scheduling policy of the underlying platform
• to "guarantee" good behaviour, you must control the threads, by
putting one to sleep, etc.
Put thread to Sleep
• To wait use the static method sleep of Thread class.
Thread.sleep(2000) // sleep for 2 seconds
• A sleeping thread can be interrupted. When this occurs an
InterruptedException occurs. You need to catch this.
• Many methods that throw InterruptedException, such as sleep, are
designed to cancel their current operation and return immediately
when an interrupt is received.
catch (InterruptedException e) {
//We've been interrupted: stop what we were doing.
return;
}
Sleep Example
public class Greet implements Runnable {
public void run() {
try {
for (int i=1; i < 10; i++) {
System.out.println(“Tick”);
Thread.sleep(1000);
}
}
catch (InterrupedException e) {
System.out.println(“Thread interrupted”);
}
}
}
join()
• The join method allows one thread to wait for the completion of
another.
• If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t's thread
terminates.
• Overloads of join allow the programmer to specify a waiting period.
• Like sleep, join responds to an interrupt with an
InterruptedException.