 2002 Prentice Hall, Inc. All rights reserved. Outline HoldIntegerUnsyn chronized.java Line 4 Lines 7-13 Lines 16-22 1 // Fig. 15.6: HoldIntegerUnsynchronized.java.

Slides:



Advertisements
Similar presentations
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Advertisements

Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
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.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
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.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
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
1 Handout 10 MULTI-THREADING BY GEORGE KOUTSOGIANNAKIS THIS DOCUMENT CAN NOT BE REPRODUCED OR DISTRIBUTED WITHOUT TH E WRITTEN PERMISSION OF THE AUTHOR.
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.
Fundamentals of Python: From First Programs Through Data Structures
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
Internet Software Development More stuff on Threads Paul Krause.
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.
 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.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
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.
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
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
Java Producer-Consumer Monitor From: Concurrent Programming: The Java Programming Language By Steven J. Hartley Oxford University Press, 1998.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
 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.
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.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
Threads in Java 1 OOutline Introduction Class Thread : An Overview of the Thread Methods Thread States: Life Cycle of a Thread Thread Priorities and Thread.
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.
MultiThreading Programming
Threads in Java Two ways to start a thread
Threaded Programming in Python
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
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Threaded Programming in Python
Component-Based Software Engineering
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

 2002 Prentice Hall, Inc. All rights reserved. Outline HoldIntegerUnsyn chronized.java Line 4 Lines 7-13 Lines // Fig. 15.6: 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

 2002 Prentice Hall, Inc. All rights reserved. Outline ProduceInteger.j ava Line 10 Lines // Fig. 15.4: 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

 2002 Prentice Hall, Inc. All rights reserved. Outline ProduceInteger.j ava Lines System.err.println( 35 getName() + " finished producing values" + 36 "\nTerminating " + getName() ); 37 } } // end class ProduceInteger Thread prints that it finished

 2002 Prentice Hall, Inc. All rights reserved. Outline ConsumeInteger.j ava Line 10 Lines Line 23 Lines // Fig. 15.5: 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

 2002 Prentice Hall, Inc. All rights reserved. Outline 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

 2002 Prentice Hall, Inc. All rights reserved. Outline SharedCell.java Lines // Fig. 15.7: 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

 2002 Prentice Hall, Inc. All rights reserved. Outline 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

 2002 Prentice Hall, Inc. All rights reserved. Producer/Consumer Relationship with Thread Synchronization Synchronize threads to ensure correct data

 2002 Prentice Hall, Inc. All rights reserved. Outline ProduceInteger.j ava Line 10 Lines // Fig. 15.8: 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

 2002 Prentice Hall, Inc. All rights reserved. Outline ProduceInteger.j ava Lines System.err.println( 35 getName() + " finished producing values" + 36 "\nTerminating " + getName() ); 37 } } // end class ProduceInteger Thread prints that it finished

 2002 Prentice Hall, Inc. All rights reserved. Outline ConsumeInteger.j ava Line 10 Lines Line 23 Lines // Fig. 15.9: 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

 2002 Prentice Hall, Inc. All rights reserved. Outline 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

 2002 Prentice Hall, Inc. All rights reserved. Outline HoldIntegerSynch ronized.java Line 6 Line 7 Lines Line 14 1 // Fig : 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

 2002 Prentice Hall, Inc. All rights reserved. Outline 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

 2002 Prentice Hall, Inc. All rights reserved. Outline HoldIntegerSynch ronized.java return sharedInt; 70 } } // end class HoldIntegerSynchronized

 2002 Prentice Hall, Inc. All rights reserved. Outline SharedCell.java Lines // Fig : 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

 2002 Prentice Hall, Inc. All rights reserved. Outline 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