Cs3180 (Prasad)L11Threads1 Concurrent Programming class Thread interface Runnable class Object.

Slides:



Advertisements
Similar presentations
wwwcsif.cs.ucdavis.edu/~jacksoni
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Object-Oriented Software Engineering Concurrent Programming.
1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.
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.
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-
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
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.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
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.
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.
CS884 (Prasad)java8Threads1 Concurrent Programming Multithreading.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
1 Web Based Programming Section 8 James King 12 August 2003.
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.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –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.
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.
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.
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.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
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.
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.
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.
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.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreaded Programming in Java
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Threads Chate Patanothai.
Multithreading Chapter 23.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreading.
Multithreaded Programming
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

cs3180 (Prasad)L11Threads1 Concurrent Programming class Thread interface Runnable class Object

cs3180 (Prasad)L11Threads2 Multiprocessing –Using Multiple Processors. Multiprogramming (Batch) –Switch and execute different jobs simultaneously, to improve CPU utilization. Multitasking (Interactive) –Perform more than one task at a time for each user, to improve response time. Multithreading –Threads in a user task (process) can share code, data, and system resources, and access them concurrently. –Each thread has a separate program counter, registers, and a run-time stack. granularity

cs3180 (Prasad)L11Threads3 Multitasking >ls >more a.txt >emacs -nw a.java >gcc a.c ; a.out >…>… >logout % ls % xclock & % netscape & % emacs a.java & % javac a.java ; java a %...

cs3180 (Prasad)L11Threads4 Browser : A Multithreaded Application Concurrent Activities: –Scrolling a page. –Downloading an applet/image over the internet. –Playing animation and sound simultaneously. –Printing a page in the background. –Updating Stock Quotes automatically. –FTP-ing a remote file. –... Browser is a mini-OS!

cs3180 (Prasad)L11Threads5 Threads in Java A single sequential flow of control (of execution of expressions and statements) is called a thread. A thread independently executes Java code, but may share address space with other threads. (cf. Process) Java primitives for concurrent programming are based on Hoare’s monitors.

cs3180 (Prasad)L11Threads6 Motivation Application independent interleaving of threads. Support Concurrent Activities Multimedia Applications Advertisements, Sports/stocks ticker Improve user response User input in interactive programs I/O in networked programs “in the background” Improve CPU utilization Demand-driven thread-scheduling

Overall Game Plan How to create and execute multiple threads? Interleaved computations Indiscriminate interleaving interferes with application semantics Introduce Mutual Exclusion constucts Example: Printing documents on a shared printer Introduce Synchronization constructs Example: Buffering on a shared printer cs3180 (Prasad)L11Threads7

Applications Requiring Concurrency Control Airline reservation system Hotel booking system Banking system Stock exchange Payroll management system Embedded systems cs3180 (Prasad)L11Threads8

cs3180 (Prasad)L11Threads9 Java Primitives Mutual exclusion synchronized methods in a class cannot be run concurrently on behalf of different threads. synchronized statement locks an object. “Object” is an instance of a class (incl. class Class ). Synchronization / Cooperation Methods wait(), notify(), notifyAll() etc. in class Object enable threads to communicate and regulate each other’s progress.

cs3180 (Prasad)L11Threads10 Creating Threads

cs3180 (Prasad)L11Threads11 Creating and Running Threads Define subclass of class Thread. Override run() method. public void run() { } Create an instance of the subclass, and invoke start() on it. Now run() method executes in an independent thread.

cs3180 (Prasad)L11Threads12 Example using class Thread class Echo extends Thread { int id; Echo(int i) { id = i; } public void run() { while (true) { System.out.println(id +“ ABC ”); // yield(); } } public static void main ( String[] args ) { new Echo(1). start(); new Echo(2). start(); } }

cs3180 (Prasad)L11Threads13 1 ABC 2 ABC 1 ABC 2 ABC 1 ABC... > javac Echo.java > java Echo 1 ABC 2 ABC 1 ABC 2 ABC 1 ABC... 1 ABC... Solaris Windows with yield() in both OS 1 ABC 2 ABC 1 ABC 2ABC 1 ABC 2 ABC 1ABC 2 ABC 1 ABC 2 ABC...

cs3180 (Prasad)L11Threads14 Alternative :Creating and Running Threads Threads can also be created from an instance of a class implementing the interface Runnable. Required when the class is defined by extension.

cs3180 (Prasad)L11Threads15 Example using interface Runnable class Echo implements Runnable { int id; Echo(int i) { id = i; } public void run() { while (true) { System.out.println(id +“ ABC ”); // yield(); } } public static void main ( String[] args ) { new Thread (new Echo(1)). start(); new Thread (new Echo(2)). start(); } }

cs3180 (Prasad)L11Threads16 Same Example in C# using System.Threading; class Echo { int id; Echo(int i) { id = i; } public void run() { while (true) System.Console.WriteLine(id + " ABC "); } public static void Main () { new Thread ( new ThreadStart (new Echo(1).run)). Start(); new Thread ( new ThreadStart (new Echo(2).run)). Start(); }

cs3180 (Prasad)L11Threads17 Alternate Rendition in Java class Echo implements Runnable { public void run() { { try { while (true) { Thread.sleep(1000); System.out.println(“ABC”); } } } catch (InterruptedException e) { return; } } public static void main (String[] args) { Runnable r = new Echo(); new Thread(r). start(); } }

cs3180 (Prasad)L11Threads18 Threads and Applets A Simple Bouncing Ball Animation

cs3180 (Prasad)L11Threads19 class Ball { static final int TOP = 10, BOTTOM = 150; int incr = 2; int ypos = TOP; void paint(java.awt.Graphics g) { if (ypos BOTTOM) incr= -incr; ypos += incr; g.setColor(java.awt.Color.cyan); g.fillOval(10,ypos, 10,10); }}

cs3180 (Prasad)L11Threads20 // public class Bounce extends java.applet.Applet { Ball b; public void init() { b = new Ball(); setBackground(java.awt.Color.red); } public void paint(java.awt.Graphics g){ b.paint(g); repaint(15); /* try { while (true) { Thread.sleep(15); repaint(); } } catch (InterruptedException e) {}; */ }

cs3180 (Prasad)L11Threads21 Threaded Applet public class ThreadedBounce extends java.applet.Applet implements Runnable { Ball b; Thread t; public void init() { b = new Ball(); setBackground (java.awt.Color.red); t = new Thread(this); t.start(); }...

cs3180 (Prasad)L11Threads22... public void paint(java.awt.Graphics g){ b.paint(g); // moved the code from here } public void run(){ try { while (true) { Thread.sleep(15); repaint(); } } catch (InterruptedException e) {}; }

cs3180 (Prasad)L11Threads23 Another version of Threaded Applet public class ThreadedColorBounce extends java.applet.Applet implements Runnable { Ball b; Thread t; public void init() { b = new Ball(); setBackground(java.awt.Color.red); } public void start() { if ( t == null) { t = new Thread(this); t.start(); }}...

cs3180 (Prasad)L11Threads24 public void stop() { t = null; } public void paint(java.awt.Graphics g){ b.paint(g); } public void run(){ try { while (true) { Thread.sleep(15); repaint(); } } catch (InterruptedException e) {}; }

cs3180 (Prasad)L11Threads25 Color Changing Ball class ColorBall extends Thread { static final int TOP = 10, BOTTOM = 150; java.awt.Color c = java.awt.Color.cyan; int incr = 2; int ypos = TOP; public ColorBall(){ start(); } void paint(java.awt.Graphics g) { if (ypos BOTTOM) incr= -incr; ypos += incr; g.setColor(c); g.fillOval(10,ypos, 10,10); }...

cs3180 (Prasad)L11Threads26... public void run() { try { while (true) { sleep(600); c = new java.awt.Color( (float) Math.random(), (float) Math.random() ); } } catch (InterruptedException e) {}; }

cs3180 (Prasad)L11Threads27 Mutual Exclusion Sharing Data

cs3180 (Prasad)L11Threads28 Threads Sharing Data class Shared { private int cnt = 0; // synchronized void print(String Id) { System.out.print(Id + “:” + cnt ); System.out.println( “-” + ++cnt); } } class Shared { private int cnt = 0; void print(String Id) { synchronized (this) { System.out.print(Id + “:” + cnt ); System.out.println( “-” + ++cnt); } } }

cs3180 (Prasad)L11Threads29 class SharingThread extends Thread { private static Shared s = new Shared(); String Id; SharingThread (String Name) { Id = Name; start(); } public void run () { while (true) { s.print(Id); // yield(); } } public static void main ( String [] args ) { new SharingThread(“A”) ; new SharingThread(“B”) ; } }

cs3180 (Prasad)L11Threads30 Motivation for Mutual Exclusion Concurrent Access Mutual Exclusion with yield() A: A: B: A: A: A: A: B: B: B: B: B:379A: A: A: A: A: B: B: A: B: A: B: A: B: B: A: B: … A: A: A: B: B: B: B: B: B: A: A: A: A:

cs3180 (Prasad)L11Threads31 // C# Equivalent using System; using System.Threading; class Shared { private int cnt = 0; public void print(String Id) { lock (this) { Console.Write(Id + ":" + cnt); Console.WriteLine("-" + ++cnt); }; } } class SharingThread { private static Shared s = new Shared(); String Id; SharingThread (String Name) { Id = Name; } public void run () { while (true) { s.print(Id); } } public static void Main (string [] args) { new Thread (new ThreadStart (new SharingThread("A").run) ). Start() ; new Thread (new ThreadStart (new SharingThread("B").run) ). Start() ; } }

cs3180 (Prasad)L11Threads32 Interaction of Language Features run() method case study

cs3180 (Prasad)L11Threads33 Subclassing : Access Control class Thread {... public void run() { } } class SubThread extends Thread { public void run() {... } /****************** ILLEGAL ******************** void run() {... } ******************* ILLEGAL ********************/ } Otherwise, run() can be invoked on a SubThread instance via (its reference in) a Thread variable (due to dynamic binding) in another package. Thread t = new SubThread(); t. run()

cs3180 (Prasad)L11Threads34 Subclassing : Exception class Thread {... public void run() { } } class SubThread extends Thread { public void run() {... } /****************** ILLEGAL ******************** public void run() throws InterruptedException { sleep(1000); } ******************* ILLEGAL ********************/ } run() invoked on a SubThread instance via a Thread variable (by dynamic binding) can violate the contract that run() of class Thread does not throw any exception. Thread t = new SubThread(); t. run()

cs3180 (Prasad)L11Threads35 Subclassing : synchronized A synchronized method can override or be overridden by a non- synchronized method. However, this does not alter “synchronized”-status of the overridden method accessible using super. The locks are released when synchronized statements and synchronized method invocations complete abruptly by throw ing an exception. vIncorporating threads in the language enables dealing with problematic interactions with other language features.

cs3180 (Prasad)L11Threads36 synchronized methods A method that is not synchronized can run concurrently with a synchronized method on behalf of different threads. The “locking”-analogy breaks down here. For concreteness, consider an example involving two threads: (i) T1 running synchronized method m1 and (ii) T2 running ordinary method m2 on the same object O. A synchronized method can call another synchronized method in the same thread. Recursion meaningful

Synchronized instance methods can run concurrently with ordinary methods on the same object. cs3180 (Prasad)L11Threads37 T1 T2 O syn m1 m2 syn m3

cs3180 (Prasad)L11Threads38 synchronized methods A synchronized instance (resp. static ) method locks instance (resp. static ) fields. A synchronized instance method does not protect static fields, and they can corrupt it thro an update. For concreteness, consider an example involving two threads T1 and T2 running synchronized instance methods m1 and m2 on objects O1 and O2 of the same class C. Both m1 and m2 are permitted to concurrently access the static fields of C, and there is potential for corruption. In such situations, static fields must be accessed in the body of instance methods using calls to synchronized static methods.

Synchronized instance methods run on distinct objects in different threads can clash on static fields. Hence, synchronized static methods are necessary to protect static fields from concurrent access. cs3180 (Prasad)L11Threads39 T1 T2 O1 syn m1 syn m2 O2 Class C

cs3180 (Prasad)L11Threads40 Thread Scheduling

cs3180 (Prasad)L11Threads41 Blocked Thread A thread is blocked (that is, it is not runnable) if it is: –sleeping. –suspended. –waiting. –executing a “blocked” method. –“blocked” for I/O. Java neither detects nor prevents deadlocks.

cs3180 (Prasad)L11Threads42 Thread Scheduling Java runs a non-blocked (runnable) highest-priority thread. A thread can be preempted by a higher priority thread that becomes runnable. –The scheduler may however choose to run lower priority thread, to avoid starvation. The same (highest) priority threads are run in round-robin fashion.

cs3180 (Prasad)L11Threads43 Scheduling Ambiguity JVM on Windows uses time-slicing to schedule same priority threads. (“Fair policy”) JVM on Solaris chooses one of the same priority threads to run until the thread voluntarily relinquishes the CPU (by sleep ing, yield ing, or exit ing), or until a higher priority thread preempts it.

cs3180 (Prasad)L11Threads44 Cooperative Concurrent Threads Producer-Consumer Problem Bounded-Buffer Problem (Clients and Servers : Resource Sharing)

cs3180 (Prasad)L11Threads45 Simplistic 1-Cell Buffer class Buffer { Object x; // synchronized public void put (Object _x, String id) { System.out.println( "Done << " + id + " puts " + _x); x = _x; } // synchronized public Object get (String id) { System.out.println( "Done >> " + id + " gets " + x); return x; } }

cs3180 (Prasad)L11Threads46 Producer-Consumer : Bounded Buffer public class PCB { public static void main(String[] args) { Buffer b = new Buffer(); new Consumer(b,"C1"). start(); new Producer(b,"P1"). start(); try {Thread.sleep(1000); } catch (Exception e){}; new Consumer(b,"C2"). start(); new Producer(b,"P2"). start(); } }

Digression : Two ways of Sharing Objects Use a static field –When instances of a class require shared object See mutual exclusion example Use instance fields initialized via constructor –When instances of different classes require a shared object See producer consumer example cs3180 (Prasad)L11Threads47

cs3180 (Prasad)L11Threads48 class Producer extends Thread { private Random r = new Random(); Buffer b; String id; public Producer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; Integer ir; try { while (true) { delay = Math.abs(r.nextInt() % 1999) + 50; sleep(delay); ir = new Integer(delay); System.out.println("Ready << "+id+" puts "+ ir); b.put(ir, id); } } catch (Exception e){System.out.println("Exception$ " + e);}; } }

cs3180 (Prasad)L11Threads49 class Consumer extends Thread { private Random r = new Random(); Buffer b; String id; public Consumer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; Integer ir = null; try { while (true) { delay = Math.abs(r.nextInt() % 1999) + 50; sleep(delay); System.out.println("Ready >> " + id + " gets "); ir = (Integer) b.get(id); } } catch (Exception e) {System.out.println("Exception$ " + e);}; } }

cs3180 (Prasad)L11Threads50 Unfettered Run Ready >> C1 gets Ready << P2 puts 493 Done >> C1 gets null Done << P2 puts 493 Ready << P1 puts 1591 Done << P1 puts 1591 Ready << P1 puts 488 Done << P1 puts 488 Ready >> C2 gets Done >> C2 gets 488 Ready >> C1 gets Done >> C1 gets 488 Ready >> C2 gets Done >> C2 gets 488 Ready << P1 puts 745 Done << P1 puts Ready << P2 puts 815 Done << P2 puts 815 Ready >> C2 gets Done >> C2 gets 815 Ready << P1 puts 1223 Done << P1 puts 1223 Ready >> C1 gets Done >> C1 gets 1223 Ready << P2 puts 403 Done << P2 puts 403 Ready >> C2 gets Done >> C2 gets (transient stability?!) premature puts gets

cs3180 (Prasad)L11Threads51 Concurrency control Concurrency control : class Buffer class Buffer { Object x; boolean empty = true; public synchronized void put (Object _x, String id) throws Exception {...} public synchronized Object get (String id) throws Exception {... } } Two producers (consumers) cannot put(get) two items in (from) the same buffer slot simultaneously. Two producers (consumers) cannot put(get) two items in (from) the same buffer slot without an intervening consumer (producer). A consumer (producer) is not permitted to get (put) an item from (into) buffer if empty (full).

cs3180 (Prasad)L11Threads52 public synchronized void put (Object _x, String id) throws Exception { while (!empty) wait(); empty = ! empty; System.out.println("Done << "+id+" puts "+ _x); x = _x; notifyAll(); } Note that if-then cannot replace while because notifyAll, due to a consumer, can wake up two wait ing producers, and only one producer will find the buffer empty. (“race condition”)

cs3180 (Prasad)L11Threads53 public synchronized Object get (String id) throws Exception { while (empty) wait(); empty = ! empty; System.out.println("Done >> "+id+" gets "+x); notifyAll(); return x; } Note that notify cannot always be used in place of notifyAll because a consumer may be woken up. while required because notifyAll due to a producer does not guarantee that wait- ing consumers will find an item in the buffer.

cs3180 (Prasad)L11Threads54 Synchonization and Mutual Exclusion Ready >> C2 gets Ready >> C1 gets Ready << P1 puts 1672 Done << P1 puts 1672 Done >> C2 gets 1672 Ready << P2 puts 774 Done << P2 puts 774 Done >> C1 gets 774 Ready << P1 puts 168 Done << P1 puts 168 Ready >> C1 gets Done >> C1 gets 168 Ready << P2 puts 1263 Done << P2 puts 1263 Ready >> C1 gets Done >> C1 gets 1263 …... Ready << P1 puts 622 Done << P1 puts 622 Ready >> C1 gets Done >> C1 gets 622 Ready >> C2 gets Ready << P2 puts 1447 Done << P2 puts 1447 Done >> C2 gets 1447 Ready << P2 puts 96 Done << P2 puts 96 Ready << P2 puts 95 Ready >> C1 gets Done >> C1 gets 96 Done << P2 puts 95...

cs3180 (Prasad)L11Threads55 Methods in class Object public final void wait() throws InterruptedException {...} Current thread is suspended (after atomically releasing the lock on this ) until some other thread invokes notify() or notifyAll() or interrupts. public final void notify() {...} Notifies exactly one thread waiting on this object for a condition to change. The awakened thread cannot proceed until this thread relinquishes the lock. public final void notifyAll() {...} –These methods must be invoked inside synchronized code or else IllegalMonitorStateException will be thrown.

cs3180 (Prasad)L11Threads56 Single Cell Buffer in C# using System; using System.Threading; class Buffer { Object x; bool empty = true; public void put (Object _x, string id) { lock(this){ while (!empty) Monitor.Wait(this); empty = ! empty; Console.WriteLine("Done << " + id + " puts " + _x); x = _x; Monitor.PulseAll(this); } public Object get (string id) { lock(this){ while (empty) Monitor.Wait(this); empty = ! empty; Console.WriteLine("Done >> " + id + " gets " + x); Monitor.PulseAll(this); return x; }

cs3180 (Prasad)L11Threads57 class Producer { private System.Random r = new System.Random(); Buffer b; String id; public Producer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; try { while (true) { delay = r.Next(2000) + 50; Thread.Sleep(delay); Console.WriteLine("Ready << " + id + " puts " + delay); b.put(delay, id); } } catch (Exception e){Console.WriteLine("Exception$ " + e);}; }

cs3180 (Prasad)L11Threads58 class Consumer { private System.Random r = new System.Random(); Buffer b; String id; public Consumer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; try { while (true) { delay = r.Next(2000) + 50; Thread.Sleep(delay); Console.WriteLine("Ready >> " + id + " gets "); delay = (int) b.get(id); } } catch (Exception e) {Console.WriteLine("Exception$ " + e);}; }

cs3180 (Prasad)L11Threads59 public class PCB { public static void Main(string[] args) { Buffer b = new Buffer(); new Thread( new ThreadStart(new Consumer(b,"C1").run)). Start(); new Thread( new ThreadStart(new Producer(b,"P1").run)). Start(); try {Thread.Sleep(1000);} catch (Exception e){Console.WriteLine("Exception$ " + e);}; new Thread( new ThreadStart(new Consumer(b,"C2").run)). Start(); new Thread( new ThreadStart(new Producer(b,"P2").run)). Start(); }