Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.

Similar presentations


Presentation on theme: "CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009."— Presentation transcript:

1 CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009

2 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

3 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

4 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

5 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

6 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 time- slice 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

7 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.

8 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"); }

9 Playing Ping Pong public class PingPong { public static void main(String[] args); Pinger pinger = new Pinger(); Ponger ponger = 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. start() starts its thread, then immediately hands back control, so that the second thread can begin. Both threads run concurrently.

10 Threads using interfaces Instead of directly subclassing Thread, we can implement the Runnable interface, by specifying the run() method 1.Create class implementing Runnable 2.Specify run() method 3.Create object of class 4.Construct a Thread object from Runnable object 5.Call the start() method of Thread Advantages of this approach Can use thread pools (see later) Inheritance is still available to your class

11 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 }

12 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 main(String[] args) { Thread t1 = new Thread(new Pinger()); Thread t2 = new Thread(new Ponger()); t1.start(); t2.start(); }

13 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.

14 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; }

15 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”); }

16 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.


Download ppt "CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009."

Similar presentations


Ads by Google