Top Banner
EE2E1. JAVA Programming Lecture 8 Lecture 8 Multi-threading Multi-threading
41

EE2E1. JAVA Programming Lecture 8 Multi-threading.

Dec 27, 2015

Download

Documents

Denis Weaver
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: EE2E1. JAVA Programming Lecture 8 Multi-threading.

EE2E1. JAVA Programming

Lecture 8Lecture 8

Multi-threadingMulti-threading

Page 2: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Contents

IntroductionIntroduction Creating a thread – the Creating a thread – the ThreadThread class class Starting and running threadsStarting and running threads Thread statesThread states Thread priorities and schedulingThread priorities and scheduling Thread synchronisationThread synchronisation The The RunnableRunnable interface interface

Page 3: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Introduction You are used to computers (operating systems) being You are used to computers (operating systems) being

multi-taskingmulti-tasking You can browse the web whilst editing your Java You can browse the web whilst editing your Java

programs!programs! Multi-tasking refers to an operating system running Multi-tasking refers to an operating system running

several several processes processes concurrentlyconcurrently Each process has its own completely independent Each process has its own completely independent

data data Multi-tasking is difficult to incorporate in application Multi-tasking is difficult to incorporate in application

programs requiring system programming primitivesprograms requiring system programming primitives

Page 4: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Java is the only commonly used programming language that enables Java is the only commonly used programming language that enables concurrency to be implemented within application programsconcurrency to be implemented within application programs Multi-threadingMulti-threading

An application program can be written as a set of An application program can be written as a set of threadsthreads which run which run concurrently (in parallel)concurrently (in parallel)

A thread is different from a process in that threads A thread is different from a process in that threads share the same share the same datadata

Switching between threadsSwitching between threads involves much less overhead than involves much less overhead than switching between programsswitching between programs

Sharing data can lead to programming complications (for Sharing data can lead to programming complications (for example in reading/writing databases)example in reading/writing databases)

Page 5: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Creating threads – the Thread class To run a piece of code in a separate thread it is To run a piece of code in a separate thread it is

placed in the placed in the run()run() method of a class which method of a class which extends extends ThreadThread

class ThreadApp extends Thread{

public void run() { // This code runs in a new thread }

public static void main(String args[]) { ThreadApp m=new ThreadApp(); m.start();

}}

Page 6: EE2E1. JAVA Programming Lecture 8 Multi-threading.

The The Thread Thread class has a class has a start() start() method method which automatically calls which automatically calls run()run()

main() thread

new thread

new thread created

Page 7: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Example

The following simple application creates The following simple application creates separate threads to update a count within a separate threads to update a count within a windowwindow

http://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java%20Stuff/ThreadTestApplet/%20Stuff/ThreadTestApplet/ThreadTestApplet.html ThreadTestApplet.html

Page 8: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Main thread

Create counter thread

Create counter thread

…..

Page 9: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Class Class CounterCounter stores the current count and a stores the current count and a frame to display the textframe to display the text

It has a a It has a a run()run() method which simply slowly method which simply slowly counts upwards within a separate threadcounts upwards within a separate thread

class Counter extends Thread{

public Counter(LabelFrame frame) {…}

public void run() {..} private int count=0; private LabelFrame labelFrame; }

Page 10: EE2E1. JAVA Programming Lecture 8 Multi-threading.

public void run(){ try {

do {

count++; labelFrame.getPanel().setCount(count); sleep(10);

labelFrame.repaint();} while (true);

} catch(InterruptedException e){}}

Page 11: EE2E1. JAVA Programming Lecture 8 Multi-threading.

public class ThreadTestFrame extends JFrame{

private int nthreads=0;

public ThreadTestFrame() { Container contentPane=getContentPane(); JPanel p=new JPanel(); addButton(p,"Start Count", new ActionListener() {

public void actionPerformed(ActionEvent evt) {

// Select frame colour Counter c=new Counter(new LabelFrame(color));

c.start(); nthreads++; }

}); contentPane.add(p,"South"); }

public void addButton(Container c, String title, ActionListener a){ // Add button to a panel }

}

Page 12: EE2E1. JAVA Programming Lecture 8 Multi-threading.

The The sleep(int t) sleep(int t) method is a static method of method is a static method of Thread Thread which puts the currently running thread to which puts the currently running thread to sleep for sleep for tt milliseconds milliseconds This allows other counters running in separate This allows other counters running in separate

threads to resume countingthreads to resume counting sleep()sleep() throws an exception when the thread is throws an exception when the thread is

interrupted by another thread wanting to run – interrupted by another thread wanting to run – hence the hence the try-catch try-catch clauseclause

Page 13: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Each Each Counter Counter object is created in the object is created in the actionPerformed()actionPerformed() method of the button method of the button attached to the outer frame (applet)attached to the outer frame (applet) The thread is started by calling the The thread is started by calling the start() start()

methodmethod The number of threads started is countedThe number of threads started is counted

in thein the nthreads nthreads variablevariable and the frame and the frame colour selected accordinglycolour selected accordingly

Page 14: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Thread states

A thread can exist in one of 4 statesA thread can exist in one of 4 states newnew

The thread has just been createdThe thread has just been created runnablerunnable

The The start()start() method has been called for method has been called for the thread and it is now ready to runthe thread and it is now ready to run

Page 15: EE2E1. JAVA Programming Lecture 8 Multi-threading.

blockedblockedEither the Either the sleep()sleep() method has been called method has been called The thread has blocked on an I/O operationThe thread has blocked on an I/O operationThe thread has called the The thread has called the wait()wait() method methodThe thread tries to lock an object that is The thread tries to lock an object that is

locked by another threadlocked by another thread deaddead

Either the Either the run()run() method for the thread has method for the thread has completed or an uncaught exception has completed or an uncaught exception has terminated the terminated the run() run() methodmethod

Page 16: EE2E1. JAVA Programming Lecture 8 Multi-threading.

new runnable

blocked

dead

start()

sleep()

run() method exits

block on I/O

Done sleeping

wait()notify()

I/O complete

Page 17: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Thread priorities and scheduling Every thread has a Every thread has a prioritypriority which can be increased which can be increased

or decreased by calling the or decreased by calling the setPriority()setPriority() method method Thread.MIN_PRIORITYThread.MIN_PRIORITY is the minimum is the minimum

priority (defined 1)priority (defined 1) Thread.MAX_PRIORITYThread.MAX_PRIORITY is the maximum is the maximum

priority (defined as 10)priority (defined as 10) When a thread is created, it is given a priority When a thread is created, it is given a priority

of 5 – defined as of 5 – defined as Thread.NORM_PRIORITYThread.NORM_PRIORITY

Page 18: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Thread scheduling Differs depending on the operating systemDiffers depending on the operating system

WindowsWindowsEach thread is given a timeslice after which it is pre-Each thread is given a timeslice after which it is pre-

empted by another thread of higher empted by another thread of higher oror equal priority equal priority UNIX, LINUXUNIX, LINUX

A thread can only be pre-empted by a thread of A thread can only be pre-empted by a thread of higher priority. If one is not available, the thread higher priority. If one is not available, the thread runs to completionruns to completion

In both cases, lower priority threads can only run if all In both cases, lower priority threads can only run if all higher priority threads are blockedhigher priority threads are blocked

Page 19: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Runnable threads Blocked threads

P=5

Blocks

Blocks

Un-blocks

P=5 P=3

Page 20: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Thread synchronisation Threads need to share access to objects and may Threads need to share access to objects and may

update shared objectsupdate shared objects For example multiple threads may access a For example multiple threads may access a

database for an online flight booking systemdatabase for an online flight booking system One thread may be updating a database entry whilst One thread may be updating a database entry whilst

another is reading it may lead to problemsanother is reading it may lead to problems We can We can synchronise synchronise threads so that they must threads so that they must

complete their action before another thread is complete their action before another thread is scheduledscheduled We do this by tagging methods as We do this by tagging methods as synchronizedsynchronized

When a synchronised method is being executed, When a synchronised method is being executed, the object is the object is lockedlocked and no other method can and no other method can access the object until the method completesaccess the object until the method completes

Page 21: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Unsynchronised threads

Thread 1 Thread 2

Update database

Read database

Pre-empt

Pre-empt

Page 22: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Synchronised threads

Thread 1 Thread 2

Update database

Read database

Page 23: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Example – An online seat reservation system

Seats for a concert can be reserved through booking agentsSeats for a concert can be reserved through booking agents

The processing for each booking agent runs in a separate thread – possibly on a The processing for each booking agent runs in a separate thread – possibly on a different processordifferent processor

Each booking transaction must check seat availability before reserving the seatEach booking transaction must check seat availability before reserving the seat

Page 24: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Seat reservation database

Booking agent 1

Booking agent 2

….. Booking agent n

Check availability

Reserve seat

Check availability

Reserve seatCheck availability

Reserve seat

Page 25: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Pseudo-code for booking a seatPseudo-code for booking a seat

if seat n is available book seat n;

Code not Code not atomicatomic For an For an unsynchronised thread unsynchronised thread it can be pre-empted by another thread after the it can be pre-empted by another thread after the if if statementstatement The thread might think the seat is available but it then might be booked by the pre-empting threadThe thread might think the seat is available but it then might be booked by the pre-empting thread The seat will be double bookedThe seat will be double booked

http://www.eee.bham.ac.uk/spannm/Java%20Stuff/SeatBookingApplet/SeatBookingApplet.html http://www.eee.bham.ac.uk/spannm/Java%20Stuff/SeatBookingApplet/SeatBookingApplet.html

Page 26: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Booking agent 1 Booking agent 2

check availability

book seat

pre-empted check availability

book seatre-schedule

Unsynchronised threads

Page 27: EE2E1. JAVA Programming Lecture 8 Multi-threading.

2 main classes2 main classes SeatBookingsSeatBookings

Contains the seat booking information (just a Contains the seat booking information (just a simple array)simple array)

Contains Contains isAvailable()isAvailable() and and bookSeat() bookSeat() methods methods which access the seat booking informationwhich access the seat booking information

BookingAgentBookingAgentExtends Extends Thread Thread and thus contains a and thus contains a run() run() methodmethodContains a reference to a Contains a reference to a SeatBookingsSeatBookings object object

which is thus a shared object between all of the which is thus a shared object between all of the BookingAgent BookingAgent objects objects

The code is as follows (code to output to frames has The code is as follows (code to output to frames has been omitted)been omitted)

Page 28: EE2E1. JAVA Programming Lecture 8 Multi-threading.

class SeatBookings{ private int[] seats; public SeatBookings(int[] s)

{ seats=s;

}

public boolean isAvailable(int seatno) {

return (seats[seatno]==0); }

public void bookSeat(int seatno) { if (isAvailable(seatno))

seats[seatno]++;}

public boolean doubleBooked(int seatno) {

return (seats[seatno]>1); }

}

Page 29: EE2E1. JAVA Programming Lecture 8 Multi-threading.

class BookingAgent extends Thread{ private SeatBookings sb; // shared object

public BookingAgent(SeatBookings s) { sb=s;

}

public void run() { do { int seatno=(int)(Math.random()*20000); sb.bookSeat(seatno);

if (sb.doubleBooked(seatno))

// generate a warning dialog

} while (true); }}

Page 30: EE2E1. JAVA Programming Lecture 8 Multi-threading.

We can synchronise the threads by tagging We can synchronise the threads by tagging the the SeatBookings.bookSeat() SeatBookings.bookSeat() method as method as synchronizedsynchronized The The SeatBookingsSeatBookings object is then object is then locked locked

by the thread which has current accessby the thread which has current access

SeatBookings object

Booking agent 1

Booking agent 2

locked locked out

Page 31: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Synchronised threads

Booking agent 1 Booking agent 2

check availability

book seat

check availability

book seat

check availability

book seat

Page 32: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Simple change to codeSimple change to code

class SeatBookings{ .

.

public synchronized void bookSeat(int seatno) {

… }

.

. }

No double booking then takes placeNo double booking then takes placehttp://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java

%20Stuff/SeatBooking%20SynchApplet/%20Stuff/SeatBooking%20SynchApplet/SeatBookingSynchApplet.html SeatBookingSynchApplet.html

Page 33: EE2E1. JAVA Programming Lecture 8 Multi-threading.

The Runnable interface So far, to develop classes which support multi-So far, to develop classes which support multi-

threading we have extended the threading we have extended the ThreadThread class and class and overwritten the overwritten the run()run() method method

This causes problems if the class is already This causes problems if the class is already extended from another classextended from another class Java doesn’t support multiple inheritanceJava doesn’t support multiple inheritance

MyClass

SuperClass Thread

Page 34: EE2E1. JAVA Programming Lecture 8 Multi-threading.

This is generally a problem if we want outer This is generally a problem if we want outer containers (containers (JFrameJFrame or or JAppletJApplet) objects to support ) objects to support multi-threadingmulti-threading

The simple solution is to make our class The simple solution is to make our class implement the implement the RunnableRunnable interface interface It would then need to implement aIt would then need to implement a run() run()

method in the usual waymethod in the usual way

class myClass extends superClass implements Runnable{ …

public void run() {…} }

Page 35: EE2E1. JAVA Programming Lecture 8 Multi-threading.

A thread is created and A thread is created and MyClass.run() MyClass.run() started as follows :started as follows :

MyClass myObject=new Myclass();

Thread t=new Thread(myObject);

t.start();

The call to The call to Thread(Runnable r)Thread(Runnable r) creates a creates a threadthread

Calling Calling Thread.start()Thread.start() then automatically then automatically calls the calls the run() run() method of the method of the RunnableRunnable objectobject

Page 36: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Example – a counter applet We will create an applet which has 2 buttonsWe will create an applet which has 2 buttons

Start CountStart Count Reset CountReset Count

The thread to do the counting must run in a The thread to do the counting must run in a separated thread to the one which handles button separated thread to the one which handles button pressespresses Swing programs create an Swing programs create an event dispatchevent dispatch

thread thread which handles all the events generated which handles all the events generated by the program (including window events for by the program (including window events for repainting graphics) repainting graphics)

Page 37: EE2E1. JAVA Programming Lecture 8 Multi-threading.

Event dispatch thread

Main thread Counting thread

Construct applet container

show container

exits

Start button pressed

Start counting …

Reset button pressed

Reset count

Page 38: EE2E1. JAVA Programming Lecture 8 Multi-threading.

The following applet doesn’t use a separate thread The following applet doesn’t use a separate thread to do the countingto do the counting Button press events or repainting events can’t be Button press events or repainting events can’t be

handled once counting beginshandled once counting beginshttp://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java

%20Stuff/CounterApplet/CounterApplet.html %20Stuff/CounterApplet/CounterApplet.html The following applet generates a separate thread The following applet generates a separate thread

for the counterfor the counterhttp://www.eee.bham.ac.uk/spannm/Javahttp://www.eee.bham.ac.uk/spannm/Java

%20Stuff/RunnableTestApplet/%20Stuff/RunnableTestApplet/RunnableTestApplet.html RunnableTestApplet.html

Page 39: EE2E1. JAVA Programming Lecture 8 Multi-threading.

public class RunnableTestApplet extends JApplet implements Runnable{ public void init() {

// Generate outer container …

addButton(p,"Start Count", new ActionListener() {

public void actionPerformed(ActionEvent evt){

startCount();}

}); addButton(p,"Reset Count", new ActionListener() { public void actionPerformed(ActionEvent evt) {

resetCount(); } });

// Add buttons to container …}

Page 40: EE2E1. JAVA Programming Lecture 8 Multi-threading.

public void startCount() { runner=new Thread(this); runner.start(); }

public void resetCount() { runner.interrupt(); count=0;

// repaint frame }

public void run() { while (!Thread.interrupted()) { count++;

// repaint frame } }

private Thread runner;} // end of class RunnableTestApplet

Page 41: EE2E1. JAVA Programming Lecture 8 Multi-threading.

And finally….. Multi-threading is complexMulti-threading is complex Make sure you understand the code for the first example we Make sure you understand the code for the first example we

looked atlooked at Run the applet from my web site and scrutinize the codeRun the applet from my web site and scrutinize the code Multi-threading is the basis of many applications and, as we Multi-threading is the basis of many applications and, as we

have seen, particularly crucial in graphical/event driven have seen, particularly crucial in graphical/event driven programmingprogramming

We have only scratched the surface. For an excellent and We have only scratched the surface. For an excellent and thorough description of threading see thorough description of threading see www.albahari.com/threading www.albahari.com/threading

In the last lab exercise, you will have the opportunity to write In the last lab exercise, you will have the opportunity to write a multi-threading server for a network-based game!a multi-threading server for a network-based game!