Threading and Concurrency COM379T John Murray –

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Definitions Process – An executing program
Threads Just Java: C10–pages 251- C11–pages 275-
Java Threads CS Introduction to Operating Systems.
Multithreading.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
1 Java Threads Instructor: Mainak Chaudhuri
MultiThreaded Applications. What is Multithreaded Programming? Having your software appear to perform multiple tasks in parallel –Individual paths of.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
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.
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.
Threads CSCE 190 – Java Instructor: Joel Gompert Wed, Aug 3, 2004.
Threading Eriq Muhammad Adams J
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.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
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
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
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.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
© 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.
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.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
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.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Multithreaded applets
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Multithreading.
Multithreaded Programming in Java
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
Principles of Software Development
Multithreading.
Java Thread.
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threading and Concurrency COM379T John Murray –

The opposite of concurrency  The following is a diagrammatic view of a ‘sequential’ program  The flow of control is linear, i.e. from one instruction to the next.

Concurrency  Concurrency consists of using multiple threads running at the same time.

Forks  When a single thread spawns another thread it is referred to as a fork.

Join  When other threads return their control back to the parent / master thread, this is known as a Join

The Thread Class  In order to be able to implement threads in Java you need to make use of the Thread class.  Therefore your class must extend Thread public class TryThread extends Thread

The Thread Class  This class provides all the methods required to run your programs threads.  Methods include: start() – Create / Initiate the thread stop() – Stop execution of the thread sleep() – Pause the thread for x time join() – Dispose of the thread in correct manor + many more, see the Thread API

run() ing a Thread  Within your class you need to create a method called run(), this is where the thread execution will start  Contains any code you wish your thread to execute.  Can call other methods from your class here.

Example – Creating two Threads public class TryThread extends Thread { private String threadName; public TryThread(String theName) {// Constructor accepting a String this.threadName = theName;// Assign string to Class attribute threadName } public static void main(String [] args) { Thread first = new TryThread(“First”);// Define first thread Thread second = new TryThread(“Second”);// Define Second thread first.start();// Start first thread second.start();// Start second thread try { System.in.read();// Wait for enter first.stop();// Stop first thread second.stop();// Stop second thread } catch (IOException e) { System.out.println(e) } public void run() { while(true) { System.out.println(“Name of thread: “ + threadName); }

Synchronization  At some point in your program several threads may wish to access a single resource.  Synchronization ensures that only one thread at any given time can access the resource.  This is known as mutual exclusion

Synchronized Methods  To make a method mutually exclusive you use the keyword synchronized synchronized public void method1() { // Code for method }  Only one of the synchronized methods in a class object can be executed by ANY thread at a time

Lets take a closer look

Thread Priorities  Threads have built-in priority scheduling.  If you wish a thread to have higher priority than others you can call the setPriority() method.  Priority’s: Low – 1 Default – 5 Highest - 10

Thread Priorities  The priority of a thread is the same as that which created it.  setPriority() accepts a type of int  IllegalArgumentException is thrown if a priority MAX_PRIORITY is set.  To find the current priority use getPriority() int currentPriority = thread1.getPriority(); // Retrieve current priority thread1.setPriority(7); // Set new Priority

Fairness of execution  If all threads have the same priority then the current thread of execution may not relinquish is control of resources, i.e. the CPU  This leads to other threads experiencing what is known as ‘starvation’.  We therefore have to make the thread relinquish it’s control of the CPU

Thread.sleep()  If you need to get a thread to free up the CPU so that other waiting threads can use it the sleep() method is called.  sleep() halts the current running of the thread and makes it release it’s access to the CPU for a set time.  Thread.sleep(timeInMilliseconds)

Runnable Interface  So far to use threads we have used extends Thread.  This could cause problems if we also need to extend JFrame for GUI’s  Therefore we can implements Runnable  The runnable interface only declares one method run()

Runnable example public class RunnableTest implements Runnable { Thread myThread;// Reference to our Thread public RunnableTest() { myThread = new Thread(this); // Create the thread myThread.start(); // Start execution of the thread } public static void main(String [] args) { RunnableTest myTest = new RunnableTest(); } public void run() { // Execute some code }

Considerations  When using threads several considerations have to be considered due to the nature of threading.  Starvation – Other lower priority threads not gaining access to CPU  Deadlock – Threads holding on to resources waiting for others <- Serious problem

Starvation  Related to priorities  Must ensure all threads will at some point get CPU time.  Keep checks on threads if not executed in x time increase priority?

Deadlock  Deadlock is a big issue in threaded systems.  It occurs when two threads are each waiting for the other thread to release control of a resource so that they can use it to complete.

Deadlock

 P1 has control of R1 but needs R2  P2 has control of R2 but needs R1  Neither P1 or P2 will release their resource.  Therefore one of the threads needs to yield() its control of the resource