University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.

Slides:



Advertisements
Similar presentations
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Advertisements

CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
More Multithreaded Programming in Java David Meredith Aalborg University.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
10/17/2015Vimal1 Threads By 10/17/2015Vimal2 Why use threads?? It is a powerful programming tool Computer users take it for granted.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Java Thread and Memory Model
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
SurfaceView.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
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.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Multithreading / Concurrency
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Chapter 19 Java Never Ends
Multithreaded Programming in Java
Multithreading.
Java Based Techhnology
Principles of Software Development
Multithreading.
Multithreaded Programming
Threads and Multithreading
Representation and Management of Data on the Internet
Concurrent programming
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems

University of Sunderland Program Threads A purely sequential (ie. non-concurrent) program contains a single control path that it follows for any given state of its data This path is referred to as a thread Begin End Instruction 1 Instruction 2 Instruction 3 Instruction 5 Instruction 4 Instruction 0

University of Sunderland Program Threads A concurrent program will consists of any number of concurrently operating threads Begin End Instruction 1 Instruction 2 Instruction 3 Instruction 5 Instruction 4 Instruction 0 Thread 1 Thread 2

University of Sunderland Fork and Join When a single thread becomes a number of additional concurrent threads it is referred to as a fork Begin Instruction 1 Instruction 0 Thread 1 Thread 2 Fork

University of Sunderland Fork and Join When any number of concurrently running threads form a single thread it is referred to as a Join End Instruction 5 Instruction 4 Thread 1 Thread 2 Join

University of Sunderland Synchronisation At some stage it is possible that a number of concurrently running threads may need to temporarily connect with each other (for example to exchange data) This requires that the threads synchronise with each other using some mechanism

University of Sunderland Java Thread Class Java provides a class that allows multi-threaded operation of Java programs This class is called Thread and is part of the java.lang package (so you do not need to import it) To support this, Java also includes the keyword synchronized to effect mutual exclusion between running threads

University of Sunderland Java Thread Mechanism To enable a Java class to operate as a thread do the following: –Write a class that extends the Thread class –Provide a run( ) method in this class that will form the concurrent operations of the class –Call the start( ) method of the class once it has been instantiated –The thread will terminate when the run( ) operation is completed

University of Sunderland An Example A program to create three independently running threads that each output a set of numbers to the console

University of Sunderland Example - Main Program Class public class ThreadExample { public static void main(String argv[]) { ThreadExample theThreadExample = new ThreadExample( ); NumDisplayer[] theNumDisplayers = new NumDisplayer[3]; for(int i = 0; i < 3; i++) { theNumDisplayers[i] = new NumDisplayer(i); // Construct each NumDisplayer theNumDisplayers[i].start( ); // Start each NumDisplayer thread (ie fork) }

University of Sunderland Example - NumDisplayer Class public class NumDisplayer extends Thread { //Extends the java.lang.Thread class int id; public NumDisplayer(int anId) { id = anId; } public void run( ) { //Method that runs when start( ) method of the this class is called for(int i = 0; i < 4; i++) System.out.println("NumDisplayer [" + id + "] displays " + i); }

University of Sunderland Example - Typical Output in MSDOS c:> java ThreadExample NumDisplayer [0] displays 0 NumDisplayer [0] displays 1 NumDisplayer [1] displays 0 NumDisplayer [2] displays 0 NumDisplayer [0] displays 2 NumDisplayer [1] displays 1 NumDisplayer [2] displays 1 NumDisplayer [0] displays 3 NumDisplayer [1] displays 2 NumDisplayer [2] displays 2 NumDisplayer [1] displays 3 NumDisplayer [2] displays 3 c:> Note how the order in which each thread displays to the console is interleaved

University of Sunderland Synchronized Keyword Any Java class method can be declared as synchronized. Once synchronized, only one thread may enter that method at anytime. Other threads wishing to do so block until the orignal thread has completed running the synchronized method. Hence you can use a synchronized method to ensure mutual exclusive access to a class’s data

University of Sunderland Use of Synchronized To make a method synchronized, use the synchronized keyword as a modifier for the method, eg. public synchronized void setData(int newData) { data = newData; } This would allow a single thread to update the data attribute of the class containing the setData() method at any given moment

University of Sunderland Example 2 using synchronized Let us adapt the previous example so the NumDisplayer objects take their value to display from another thread based upon a class called NumCounter

University of Sunderland Example 2 - Main Program Class public class ThreadExample2 { public static void main(String argv[]) { ThreadExample2 theThreadExample = new ThreadExample2( ); NumCounter theNumCounter = new NumCounter( ); // Construct the NumCounter theNumCounter.start( ); // Start the NumCounter NumDisplayer2[] theNumDisplayers = new NumDisplayer2[3]; for(int i = 0; i < 3; i++) { theNumDisplayers[i] = new NumDisplayer2(i, theNumCounter); // Construct each NumDisplayer theNumDisplayers[i].start( ); // Start each NumDisplayer }

University of Sunderland Example 2 - NumCounter Class public class NumCounter extends Thread { int counter; public NumCounter( ) { counter = 0; } public synchronized int getNextNum( ) { int currentNum = counter; updateCounter( ); return currentNum; } public synchronized void updateCounter( ) { counter++; } public void run( ) { while(true) { //Go on and on... try { Thread.sleep(100); // Let other threads operate, see later } catch(InterruptedException ie) { // Required because this exception is thrown by Thread.sleep( ) }

University of Sunderland Example – NumDisplayer2 Class public class NumDisplayer2 extends Thread { int id; NumCounter theNumCounter; // Reference to the NumCounter public NumDisplayer2(int anId, NumCounter aNumCounter) { id = anId; theNumCounter = aNumCounter; } public void run( ) { for(int i = 0; i < 4; i++) System.out.println("NumDisplayer [" + id + "] displays " + theNumCounter.getNextNum( )); }

University of Sunderland Example - Typical Output in MSDOS c:> java ThreadExample2 NumDisplayer [0] displays 0 NumDisplayer [2] displays 1 NumDisplayer [1] displays 2 NumDisplayer [0] displays 3 NumDisplayer [1] displays 4 NumDisplayer [2] displays 5 NumDisplayer [0] displays 6 NumDisplayer [0] displays 7 NumDisplayer [2] displays 8 NumDisplayer [1] displays 9 NumDisplayer [1] displays 10 NumDisplayer [2] displays 11 c:> Note how the order in which each thread displays to the console is still interleaved and that any thread can output any of the possible numbers. This is because we have no control over the sequence that the threads operate in.

University of Sunderland Thread Scheduling Notice that the previous example ensures mutual exclusion, but what about scheduling? Java has a pre-emptive, priority-based thread scheduler This means that if a higher priority thread needs the CPU, a currently running lower priority thread will be interrupted

University of Sunderland Fairness If all threads are of equal priority, then the currently running thread will not be interrupted and get exclusive use of the CPU. Thus we get an unfair scheduling of equal (or lesser) priority threads Because of this, a thread must periodically relinquish its use of the CPU in consideration of other threads

University of Sunderland Thread.sleep( ) To achieve this fairness in your Java programs, use the static method Thread.sleep( ) to temporarily halt any long running thread. This allows other threads access to the CPU. The method takes an integer value parameter that represents the time (in milliseconds) the thread will halt. 100 is a good value for this. Note: the Thread.sleep( ) method throws an InterruptedException exception, so this must be caught

University of Sunderland Thread.sleep( ) Example The NumCounter class used previously introduced a Thread.sleep( ) method call within its run( ) method. (See the previous ThreadExample2 slides)

University of Sunderland Runnable Interface The previous examples have used the idea of extension to enable a class to run as a thread. This is problematic if the class must also extend another class (such as JFrame) To overcome this, you can make the class implement the Runnable interface, which allows the class to be considered a thread

University of Sunderland Runnable Interface The Runnable Interface contains a single run( ) method that needs to be implemented (as per any thread) Once a class implements the Runnable interface, you can construct a thread for this class by passing its class reference to the Thread class constructor Once the thread is started, the run( ) method of the class will be called

University of Sunderland Runnable Interface Example For example public class ThreadExample3 implements Runnable { Thread myThread; // Reference to the thread this object will run upon public ThreadExample3( ) { myThread = new Thread(this); // Construct the thread myThread.start( ); // Start the thread, ie call the run( ) method of the ThreadExample3 class } public static void main(String argv[]) { ThreadExample3 theThreadExample = new ThreadExample3; } public void run( ) { while(true) { // do something, and use Thread.sleep( ) to show consideration to other threads }

University of Sunderland Thread Death Threads stop running under three circumstances: 1. The run( ) method completes 2. You call the stop( ) method of the thread (note this is now a deprecated method so don’t use it!) 3. The whole process within which the thread is running is terminated (i.e. when the Java VM completes) Since we have to control the lifespan of a thread through the run( ) method, it is prudent to make this method come under direct control also by using a completion flag

University of Sunderland Completion Flag Use a boolean variable to indicate whether the thread has completed or not. Use this as the condition for the while statement in the run( ) method, eg. boolean completed = false; public void run( ) { while(!completed) { …. } }

University of Sunderland Is This All? No. The subject of Java threads is large and impossible to do it justice in a single session. There will be more. You can find out more in the Java Tutorial and in most of the Java texts For a near complete treatment of the subject, consult “Java Threads”, Scott Oaks & Henry Wong, O’Reilly, 1997 “Concurrent Programming in Java”, Doug Lea, Addison Wesley, 2000