Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.

Slides:



Advertisements
Similar presentations
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
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.
1 Lecture 18 Further Threading Overview  Case Study: Cooperating Threads  Producer/ Consumer model threads  Waiting for Synchronized Data  Busy Waiting.
Java threads Threaded class extends thread Synchronized class is a monitor Runnable interface gives thread methods All code is (C) Copyright 1999 by Deitel.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
11-Jun-15 Producer-Consumer An example of using Threads.
16-Jun-15 Producer-Consumer An example of using Threads.
Multithreading. Introduction Performing operations concurrently (in parallel) –We can walk, talk, breathe, see, hear, smell... all at the same time –Computers.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
 2002 Prentice Hall, Inc. All rights reserved. Week 4 – Multithreading Outline 4.1 Introduction 4.2 Class Thread : An Overview of the Thread Methods 4.3.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
Threads Just Java: C10–pages 251- C11–pages 275-
1 Handout 10 MULTI-THREADING BY GEORGE KOUTSOGIANNAKIS THIS DOCUMENT CAN NOT BE REPRODUCED OR DISTRIBUTED WITHOUT TH E WRITTEN PERMISSION OF THE AUTHOR.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Internet Software Development More stuff on Threads Paul Krause.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Threads some important concepts Simon Lynch
Threads in Java a tutorial introduction PdD Marco Antonio Ramos Corchado February 2009.
 2002 Prentice Hall. All rights reserved. 1 Chapter 14 – Multithreading Outline 14.1 Introduction 14.2 Thread States: Life Cycle of a Thread 14.3 Thread.
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 16 – Multithreading Outline 16.1 Introduction 16.2 Thread States: Life Cycle of a Thread 16.3 Thread.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
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.
 2002 Prentice Hall, Inc. All rights reserved. Introduction Concurrency normally available in OS primitives Java provides built-in multithreading –Multithreading.
Threading Eriq Muhammad Adams J
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Threaded Programming in Python Adapted from Fundamentals of Python: From First Programs Through Data Structures CPE 401 / 601 Computer Network Systems.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
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.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
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
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Advanced Programming, Based on LY Stefanus’s slides slide 7.1 Multithreading : Using the Runnable interface.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 16 – Multithreading Outline 16.1 Introduction 16.2 Thread States: Life Cycle of a Thread 16.3.
 2002 Prentice Hall, Inc. All rights reserved. Outline HoldIntegerUnsyn chronized.java Line 4 Lines 7-13 Lines // Fig. 15.6: HoldIntegerUnsynchronized.java.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Java Thread Programming
MultiThreading Programming
Multithreading / Concurrency
Threaded Programming in Python
Chapter 13: Multithreading
Multithreading.
THREADS.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Threads II IS
Chapter 15 - Multithreading
Multithreading Chapter 23.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Chapter 15 Multithreading
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer Consumer thread –Reads message from buffer Without synchronization, it is possible to produce corrupted data

ProduceInteger.j ava Line 10 Lines // ProduceInteger.java 2 // Definition of threaded class ProduceInteger 3 public class ProduceInteger extends Thread { 4 private HoldIntegerUnsynchronized sharedObject; 5 6 // initialize ProduceInteger thread object 7 public ProduceInteger( HoldIntegerUnsynchronized shared ) 8 { 9 super( "ProduceInteger" ); 10 sharedObject = shared; 11 } // ProduceInteger thread loops 10 times and calls 14 // sharedObject's setSharedInt method each time 15 public void run() 16 { 17 for ( int count = 1; count <= 10; count++ ) { // sleep for a random interval 20 try { 21 Thread.sleep( ( int ) ( Math.random() * 3000 ) ); 22 } // process InterruptedException during sleep 25 catch( InterruptedException exception ) { 26 System.err.println( exception.toString() ); 27 } // call sharedObject method from this 30 // thread of execution 31 sharedObject.setSharedInt( count ); 32 } Instance variable sharedObject refers to object shared Method run loops 10 times, sleep ing 0-3 seconds and calling setSharedInt

ProduceInteger.j ava Lines System.err.println( 35 getName() + " finished producing values" + 36 "\nTerminating " + getName() ); 37 } } // end class ProduceInteger Thread prints that it finished

ConsumeInteger.j ava Line 10 Lines Line 23 Lines // ConsumeInteger.java 2 // Definition of threaded class ConsumeInteger 3 public class ConsumeInteger extends Thread { 4 private HoldIntegerUnsynchronized sharedObject; 5 6 // initialize ConsumerInteger thread object 7 public ConsumeInteger( HoldIntegerUnsynchronized shared ) 8 { 9 super( "ConsumeInteger" ); 10 sharedObject = shared; 11 } // ConsumeInteger thread loops until it receives // from sharedObject's getSharedInt method 15 public void run() 16 { 17 int value, sum = 0; do { // sleep for a random interval 22 try { 23 Thread.sleep( (int) ( Math.random() * 3000 ) ); 24 } // process InterruptedException during sleep 27 catch( InterruptedException exception ) { 28 System.err.println( exception.toString() ); 29 } value = sharedObject.getSharedInt(); 32 sum += value; } while ( value != 10 ); Initializes sharedObject to refer to object shared Method run contains a do / while structure that loops 10 times Each iteration causes the thread to sleep 0-3 seconds Call method getSharedInt and assign to variable sum

ConsumeInteger.j ava Lines System.err.println( 37 getName() + " retrieved values totaling: " + sum + 38 "\nTerminating " + getName() ); 39 } } // end class ConsumeInteger Thread prints that it is done consuming

HoldIntegerUnsyn chronized.java Line 4 Lines 7-13 Lines // HoldIntegerUnsynchronized.java 2 // Definition of class HoldIntegerUnsynchronized. 3 public class HoldIntegerUnsynchronized { 4 private int sharedInt = -1; 5 6 // unsynchronized method to place value in sharedInt 7 public void setSharedInt( int value ) 8 { 9 System.err.println( Thread.currentThread().getName() + 10 " setting sharedInt to " + value ); sharedInt = value; 13 } // unsynchronized method return sharedInt's value 16 public int getSharedInt() 17 { 18 System.err.println( Thread.currentThread().getName() + 19 " retrieving sharedInt value " + sharedInt ); return sharedInt; 22 } } // end class HoldIntegerUnsynchronized Instance variable sharedInt is the shared buffer Method setSharedInt not synchronized Method getSharedInt not synchronized

SharedCell.java Lines // SharedCell.java 2 // Show multiple threads modifying shared object. 3 public class SharedCell { 4 5 // execute application 6 public static void main( String args[] ) 7 { 8 HoldIntegerUnsynchronized sharedObject = 9 new HoldIntegerUnsynchronized(); // create threads 12 ProduceInteger producer = 13 new ProduceInteger( sharedObject ); 14 ConsumeInteger consumer = 15 new ConsumeInteger( sharedObject ); // start threads 18 producer.start(); 19 consumer.start(); 20 } } // end class SharedCell Method main creates a ProduceInteger thread and a ConsumeInteger thread and starts them

Program Output ConsumeInteger retrieving sharedInt value -1 ProduceInteger setting sharedInt to 1 ProduceInteger setting sharedInt to 2 ConsumeInteger retrieving sharedInt value 2 ProduceInteger setting sharedInt to 3 ProduceInteger setting sharedInt to 4 ProduceInteger setting sharedInt to 5 ConsumeInteger retrieving sharedInt value 5 ProduceInteger setting sharedInt to 6 ProduceInteger setting sharedInt to 7 ProduceInteger setting sharedInt to 8 ConsumeInteger retrieving sharedInt value 8 ProduceInteger setting sharedInt to 9 ConsumeInteger retrieving sharedInt value 9 ProduceInteger setting sharedInt to 10 ProduceInteger finished producing values Terminating ProduceInteger ConsumeInteger retrieving sharedInt value 10 ConsumeInteger retrieved values totaling: 49 Terminating ConsumeInteger Output of numbers is not properly synchronized

Thread Synchronization Java uses monitors for thread synchronization The synchronized keyword –Every object has a monitor –One thread inside a synchronized method at a time Locking –All other threads block until method finishes –Next highest priority thread runs when method finishes

Producer/Consumer Relationship with Thread Synchronization Synchronize threads to ensure correct data Producer thread –Calls wait if consumer has not read last message in buffer –Writes to empty buffer and calls notify for consumer Consumer thread –Calls wait if buffer empty

ProduceInteger.j ava Line 10 Lines // ProduceInteger.java 2 // Definition of threaded class ProduceInteger 3 public class ProduceInteger extends Thread { 4 private HoldIntegerSynchronized sharedObject; 5 6 // initialize ProduceInteger thread object 7 public ProduceInteger( HoldIntegerSynchronized shared ) 8 { 9 super( "ProduceInteger" ); 10 sharedObject = shared; 11 } // ProduceInteger thread loops 10 times and calls 14 // sharedObject's setSharedInt method each time 15 public void run() 16 { 17 for ( int count = 1; count <= 10; count++ ) { // sleep for a random interval 20 try { 21 Thread.sleep( ( int ) ( Math.random() * 3000 ) ); 22 } // process InterruptedException during sleep 25 catch( InterruptedException exception ) { 26 System.err.println( exception.toString() ); 27 } // call sharedObject method from this 30 // thread of execution 31 sharedObject.setSharedInt( count ); 32 } 33 Instance variable sharedObject refers to object shared Method run loops 10 times, sleep ing 0-3 seconds and calling setSharedInt

ProduceInteger.j ava Lines System.err.println( 35 getName() + " finished producing values" + 36 "\nTerminating " + getName() ); 37 } } // end class ProduceInteger Thread prints that it finished

ConsumeInteger.j ava Line 10 Lines Line 23 Lines // ConsumeInteger.java 2 // Definition of threaded class ConsumeInteger 3 public class ConsumeInteger extends Thread { 4 private HoldIntegerSynchronized sharedObject; 5 6 // initialize ConsumerInteger thread object 7 public ConsumeInteger( HoldIntegerSynchronized shared ) 8 { 9 super( "ConsumeInteger" ); 10 sharedObject = shared; 11 } // ConsumeInteger thread loops until it receives // from sharedObject's getSharedInt method 15 public void run() 16 { 17 int value, sum = 0; do { // sleep for a random interval 22 try { 23 Thread.sleep( (int) ( Math.random() * 3000 ) ); 24 } // process InterruptedException during sleep 27 catch( InterruptedException exception ) { 28 System.err.println( exception.toString() ); 29 } value = sharedObject.getSharedInt(); 32 sum += value; } while ( value != 10 ); Initializes sharedObject to refer to object shared Method run contains a do / while structure that loops 10 times Each iteration causes the thread to sleep 0-3 seconds Call method getSharedInt and assign to variable sum

ConsumeInteger.j ava Lines System.err.println( 37 getName() + " retrieved values totaling: " + sum + 38 "\nTerminating " + getName() ); 39 } } // end class ConsumeInteger Thread prints that it is done consuming

HoldIntegerSynch ronized.java Line 6 Line 7 Lines Line 14 1 // HoldIntegerSynchronized.java 2 // Definition of class HoldIntegerSynchronized that 3 // uses thread synchronization to ensure that both 4 // threads access sharedInt at the proper times. 5 public class HoldIntegerSynchronized { 6 private int sharedInt = -1; 7 private boolean writeable = true; // condition variable 8 9 // synchronized method allows only one thread at a time to 10 // invoke this method to set the value for a particular 11 // HoldIntegerSynchronized object 12 public synchronized void setSharedInt( int value ) 13 { 14 while ( !writeable ) { // not the producer's turn // thread that called this method must wait 17 try { 18 wait(); 19 } // process Interrupted exception while thread waiting 22 catch ( InterruptedException exception ) { 23 exception.printStackTrace(); 24 } 25 } System.err.println( Thread.currentThread().getName() + 28 " setting sharedInt to " + value ); // set new sharedInt value 31 sharedInt = value; 32 Variable sharedInt represents the shared buffer Variable writeable is the monitor condition variable Method setSharedInt now synchronized Check if sharedInt can be written

HoldIntegerSynch ronized.java Lines Line // indicate that producer cannot store another value until 34 // a consumer retrieve current sharedInt value 35 writeable = false; // tell a waiting thread to become ready 38 notify(); 39 } // synchronized method allows only one thread at a time to 42 // invoke this method to get the value for a particular 43 // HoldIntegerSynchronized object 44 public synchronized int getSharedInt() 45 { 46 while ( writeable ) { // not the consumer's turn // thread that called this method must wait 49 try { 50 wait(); 51 } // process Interrupted exception while thread waiting 54 catch ( InterruptedException exception ) { 55 exception.printStackTrace(); 56 } 57 } // indicate that producer cant store another value 60 // because a consumer just retrieved sharedInt value 61 writeable = true; // tell a waiting thread to become ready 64 notify(); System.err.println( Thread.currentThread().getName() + 67 " retrieving sharedInt value " + sharedInt ); Method getSharedInt now synchronized Check if sharedInt can be read

HoldIntegerSynch ronized.java return sharedInt; 70 } } // end class HoldIntegerSynchronized

SharedCell.java Lines // SharedCell.java 2 // Show multiple threads modifying shared object. 3 public class SharedCell { 4 5 // execute application 6 public static void main( String args[] ) 7 { 8 HoldIntegerSynchronized sharedObject = 9 new HoldIntegerSynchronized(); // create threads 12 ProduceInteger producer = 13 new ProduceInteger( sharedObject ); 14 ConsumeInteger consumer = 15 new ConsumeInteger( sharedObject ); // start threads 18 producer.start(); 19 consumer.start(); 20 } } // end class SharedCell Method main creates a ProduceInteger thread and a ConsumeInteger thread and starts them

Program Output ProduceInteger setting sharedInt to 1 ConsumeInteger retrieving sharedInt value 1 ProduceInteger setting sharedInt to 2 ConsumeInteger retrieving sharedInt value 2 ProduceInteger setting sharedInt to 3 ConsumeInteger retrieving sharedInt value 3 ProduceInteger setting sharedInt to 4 ConsumeInteger retrieving sharedInt value 4 ProduceInteger setting sharedInt to 5 ConsumeInteger retrieving sharedInt value 5 ProduceInteger setting sharedInt to 6 ConsumeInteger retrieving sharedInt value 6 ProduceInteger setting sharedInt to 7 ConsumeInteger retrieving sharedInt value 7 ProduceInteger setting sharedInt to 8 ConsumeInteger retrieving sharedInt value 8 ProduceInteger setting sharedInt to 9 ConsumeInteger retrieving sharedInt value 9 ProduceInteger setting sharedInt to 10 ProduceInteger finished producing values Terminating ProduceInteger ConsumeInteger retrieving sharedInt value 10 ConsumeInteger retrieved values totaling: 55 Terminating ConsumeInteger Output of numbers is properly synchronized

Two cases of waiting Waiting threads that are blocked because the monitor was busy Waiting threads that explicitly called wait inside the monitor