EE2E1. JAVA Programming Lecture 8 Multi-threading.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Chris Greenhalgh School of Computer Science
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Object Oriented Programming Multithreading Dr. Mike Spann
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
Concurrent Programming and Threads Threads Blocking a User Interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading in JAVA
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java Thread and Memory Model
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
SurfaceView.
Java 3: Odds & Ends Advanced Programming Techniques.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Object Oriented Programming Multithreading Dr. Mike Spann
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Lecture 9 Object Oriented Programming Using Java
CSE 501N Fall ‘09 21: Introduction to Multithreading
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
9. Threads SE2811 Software Component Design
Chapter 15 Multithreading
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
9. Threads SE2811 Software Component Design
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

EE2E1. JAVA Programming Lecture 8 Multi-threading

Contents Introduction Introduction Creating a thread – the Thread class Creating a thread – the Thread class Starting and running threads Starting and running threads Thread states Thread states Thread priorities and scheduling Thread priorities and scheduling Thread synchronisation Thread synchronisation The Runnable interface The Runnable interface

Introduction You are used to computers (operating systems) being multi-tasking You are used to computers (operating systems) being multi-tasking  You can browse the web whilst editing your Java programs! Multi-tasking refers to an operating system running several processes concurrently Multi-tasking refers to an operating system running several processes concurrently  Each process has its own completely independent data  Multi-tasking is difficult to incorporate in application programs requiring system programming primitives

Java is the only commonly used programming language that enables concurrency to be implemented within application programs Java is the only commonly used programming language that enables concurrency to be implemented within application programs  Multi-threading An application program can be written as a set of threads which run concurrently (in parallel) An application program can be written as a set of threads which run concurrently (in parallel) A thread is different from a process in that threads share the same data A thread is different from a process in that threads share the same data  Switching between threads involves much less overhead than switching between programs  Sharing data can lead to programming complications (for example in reading/writing databases)

Creating threads – the Thread class To run a piece of code in a separate thread it is placed in the run() method of a class which extends Thread To run a piece of code in a separate thread it is placed in the run() method of a class which extends Thread 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(); }

The Thread class has a start() method which automatically calls run() The Thread class has a start() method which automatically calls run() main() thread new thread new thread created

Example The following simple application creates separate threads to update a count within a window The following simple application creates separate threads to update a count within a window 0Stuff/ThreadTestApplet/ThreadTestApplet.html 0Stuff/ThreadTestApplet/ThreadTestApplet.html 0Stuff/ThreadTestApplet/ThreadTestApplet.html 0Stuff/ThreadTestApplet/ThreadTestApplet.html

Main thread Create counter thread …..

Class Counter stores the current count and a frame to display the text Class Counter stores the current count and a frame to display the text It has a a run() method which simply slowly counts upwards within a separate thread It has a a run() method which simply slowly counts upwards within a separate thread class Counter extends Thread { public Counter(LabelFrame frame) {…} public void run() {..} private int count=0; private LabelFrame labelFrame; }

public void run() { try { do { count++; labelFrame.getPanel().setCount(count); sleep(10); labelFrame.repaint(); } while (true); } catch(InterruptedException e){} }

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

The sleep(int t) method is a static method of Thread which puts the currently running thread to sleep for t milliseconds The sleep(int t) method is a static method of Thread which puts the currently running thread to sleep for t milliseconds  This allows other counters running in separate threads to resume counting  sleep() throws an exception when the thread is interrupted by another thread wanting to run – hence the try-catch clause

Each Counter object is created in the actionPerformed() method of the button attached to the outer frame (applet) Each Counter object is created in the actionPerformed() method of the button attached to the outer frame (applet)  The thread is started by calling the start() method  The number of threads started is counted in the nthreads variable and the frame colour selected accordingly

Thread states A thread can exist in one of 4 states A thread can exist in one of 4 states  new  The thread has just been created  runnable  The start() method has been called for the thread and it is now ready to run

 blocked  Either the sleep() method has been called  The thread has blocked on an I/O operation  The thread has called the wait() method  The thread tries to lock an object that is locked by another thread  dead  Either the run() method for the thread has completed or an uncaught exception has terminated the run() method

new runnable blocked dead start() sleep() run() method exits block on I/O Done sleeping wait() notify() I/O complete

Thread priorities and scheduling Every thread has a priority which can be increased or decreased by calling the setPriority() method Every thread has a priority which can be increased or decreased by calling the setPriority() method  Thread.MIN_PRIORITY is the minimum priority (defined 1)  Thread.MAX_PRIORITY is the maximum priority (defined as 10)  When a thread is created, it is given a priority of 5 – defined as Thread.NORM_PRIORITY

Thread scheduling Differs depending on the operating system Differs depending on the operating system  Windows  Each thread is given a timeslice after which it is pre-empted by another thread of higher or equal priority  UNIX, LINUX  A thread can only be pre-empted by a thread of higher priority. If one is not available, the thread runs to completion In both cases, lower priority threads can only run if all higher priority threads are blocked In both cases, lower priority threads can only run if all higher priority threads are blocked

Runnable threadsBlocked threads P=5 Blocks Un-blocks P=5P=3

Thread synchronisation Threads need to share access to objects and may update shared objects Threads need to share access to objects and may update shared objects  For example multiple threads may access a database for an online flight booking system  One thread may be updating a database entry whilst another is reading it may lead to problems We can synchronise threads so that they must complete their action before another thread is scheduled We can synchronise threads so that they must complete their action before another thread is scheduled  We do this by tagging methods as synchronized  When a synchronised method is being executed, the object is locked and no other method can access the object until the method completes

Unsynchronised threads Thread 1Thread 2 Update database Read database Pre-empt

Synchronised threads Thread 1Thread 2 Update database Read database

Example – An online seat reservation system Seats for a concert can be reserved through booking agents Seats for a concert can be reserved through booking agents The processing for each booking agent runs in a separate thread – possibly on a different processor The processing for each booking agent runs in a separate thread – possibly on a different processor Each booking transaction must check seat availability before reserving the seat Each booking transaction must check seat availability before reserving the seat

Seat reservation database Booking agent 1 Booking agent 2 ….. Booking agent n Check availability Reserve seat Check availability Reserve seat Check availability Reserve seat

Pseudo-code for booking a seat Pseudo-code for booking a seat if seat n is available book seat n; Code not atomic Code not atomic  For an unsynchronised thread it can be pre- empted by another thread after the if statement  The thread might think the seat is available but it then might be booked by the pre-empting thread  The seat will be double booked /SeatBookingApplet/SeatBookingApplet.html /SeatBookingApplet/SeatBookingApplet.html /SeatBookingApplet/SeatBookingApplet.html /SeatBookingApplet/SeatBookingApplet.html

Booking agent 1 Booking agent 2 check availability book seat pre-empted check availability book seat re-schedule Unsynchronised threads

2 main classes 2 main classes  SeatBookings  Contains the seat booking information (just a simple array)  Contains isAvailable() and bookSeat() methods which access the seat booking information  BookingAgent  Extends Thread and thus contains a run() method  Contains a reference to a SeatBookings object which is thus a shared object between all of the BookingAgent objects The code is as follows (code to output to frames has been omitted) The code is as follows (code to output to frames has been omitted)

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

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

We can synchronise the threads by tagging the SeatBookings.bookSeat() method as synchronized We can synchronise the threads by tagging the SeatBookings.bookSeat() method as synchronized  The SeatBookings object is then locked by the thread which has current access SeatBookings object Booking agent 1 Booking agent 2 locked locked out

Synchronised threads Booking agent 1Booking agent 2 check availability book seat check availability book seat check availability book seat

Simple change to code Simple change to code class SeatBookings {. public synchronized void bookSeat(int seatno) { … }. } No double booking then takes place No double booking then takes place  Stuff/SeatBooking%20SynchApplet/SeatBook ingSynchApplet.html Stuff/SeatBooking%20SynchApplet/SeatBook ingSynchApplet.html Stuff/SeatBooking%20SynchApplet/SeatBook ingSynchApplet.html

The Runnable interface So far, to develop classes which support multi- threading we have extended the Thread class and overwritten the run() method So far, to develop classes which support multi- threading we have extended the Thread class and overwritten the run() method This causes problems if the class is already extended from another class This causes problems if the class is already extended from another class  Java doesn’t support multiple inheritance MyClass SuperClassThread

This is generally a problem if we want outer containers (JFrame or JApplet) objects to support multi-threading This is generally a problem if we want outer containers (JFrame or JApplet) objects to support multi-threading The simple solution is to make our class implement the Runnable interface The simple solution is to make our class implement the Runnable interface  It would then need to implement a run() method in the usual way class myClass extends superClass implements Runnable { … public void run() {…} }

A thread is created and MyClass.run() started as follows : A thread is created and MyClass.run() started as follows : MyClass myObject=new Myclass(); Thread t=new Thread(myObject); t.start(); The call to Thread(Runnable r) creates a thread The call to Thread(Runnable r) creates a thread  Calling Thread.start() then automatically calls the run() method of the Runnable object

Example – a counter applet We will create an applet which has 2 buttons We will create an applet which has 2 buttons  Start Count  Reset Count The thread to do the counting must run in a separated thread to the one which handles button presses The thread to do the counting must run in a separated thread to the one which handles button presses  Swing programs create an event dispatch thread which handles all the events generated by the program (including window events for repainting graphics)

Event dispatch thread Main threadCounting thread Construct applet container show container exits Start button pressed Start counting … Reset button pressed Reset count

The following applet doesn’t use a separate thread to do the counting The following applet doesn’t use a separate thread to do the counting  Button press events or repainting events can’t be handled once counting begins  0Stuff/CounterApplet/CounterApplet.html 0Stuff/CounterApplet/CounterApplet.html 0Stuff/CounterApplet/CounterApplet.html  The following applet generates a separate thread for the counter  0Stuff/RunnableTestApplet/RunnableTestAp plet.html 0Stuff/RunnableTestApplet/RunnableTestAp plet.html 0Stuff/RunnableTestApplet/RunnableTestAp plet.html

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

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

And finally….. Multi-threading is complex Multi-threading is complex Make sure you understand the code for the first example we looked at Make sure you understand the code for the first example we looked at Run the applet from my web site and scrutinize the code Run the applet from my web site and scrutinize the code Multi-threading is the basis of many applications and, as we have seen, particularly crucial in graphical/event driven programming Multi-threading is the basis of many applications and, as we have seen, particularly crucial in graphical/event driven programming We have only scratched the surface. For an excellent and thorough description of threading see We have only scratched the surface. For an excellent and thorough description of threading see In the last lab exercise, you will have the opportunity to write a multi-threading server for a network-based game! In the last lab exercise, you will have the opportunity to write a multi-threading server for a network-based game!