28-Jun-15 Producer-Consumer An example of using Threads.

Slides:



Advertisements
Similar presentations
Class 18: Concurrency on Mars Fall 2010 UVa David Evans cs2220: Engineering Software Image: Michael Dewey-Vogt.
Advertisements

Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
1 Lecture 18 Further Threading Overview  Case Study: Cooperating Threads  Producer/ Consumer model threads  Waiting for Synchronized Data  Busy Waiting.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
CS 11 java track: lecture 7 This week: Web tutorial:
11-Jun-15 Producer-Consumer An example of using Threads.
16-Jun-15 Producer-Consumer An example of using Threads.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Definitions Process – An executing program
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.
© 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.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threading Eriq Muhammad Adams J
Synchronizing threads, thread pools, etc.
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.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
1 G53SRP: Clocks and Time in Java Chris Greenhalgh School of Computer Science.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
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.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
 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.
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.
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
SCJP 9/10 Threads.
Multithreading / Concurrency
Threaded Programming in Python
Multi Threading.
Threads Chate Patanothai.
Класс Object Макаревич Л. Г..
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Multithreading.
Sampath Kumar S Assistant Professor, SECE
Computer Science 2 06A-Java Multithreading
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

28-Jun-15 Producer-Consumer An example of using Threads

The problem One Thread, the producer, is “producing” information (creating objects), while another Thread, the consumer, is “consuming” (using) it We want the consumer to use the objects in the same order as the producer creates them We don’t want either Thread to be “loafing”—if there is work for it to do, the Thread should be doing it We want to absolutely avoid busy loops Example busy loop: while (!ready) { } (the other Thread will reset the ready variable) Busy loops will consume all available CPU cycles and seriously slow down everything on the computer

The overall structure import java.util.Vector; public class CommandList { static Vector list = new Vector(); public static void put(String s) { // code on next slide } public static String get() { // code on slide after next } }

Methods in java.lang.Object void wait() Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. void wait(long timeout) Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. void notify() Wakes up a single thread that is waiting on this object's monitor. void notifyAll() Wakes up all threads that are waiting on this object's monitor.

The put method public static void put(String s) { synchronized (list) { list.add(s); list.notify(); } } The synchronized(list) block will take the list object as soon as it becomes available, and “lock” it so no other synchronized(list) can use it until this block is completed There is nothing special about the list object; any object can be locked for synchronization

The get method public static String get() { if (list.size() > 0) { synchronized (list) { return (String)list.remove(0); } } else { try { synchronized (list) { list.wait(); return get(); } } catch (InterruptedException e) { return "InterruptedException"; } } } }

The Consumer class public class Consumer extends Thread { public void run() { while (true) { String s = CommandList.get(); System.out.println("Consuming " + s); } } }

The test class public class CommandListTester { public static void main(String[] args) { Consumer consumer = new Consumer(); consumer.start(); CommandList.put("one"); CommandList.put("two"); sleep(2000); CommandList.put("three"); CommandList.put("four"); } private static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } } } Output:  Consuming one  Consuming two  Consuming three  Consuming four

Another Consumer class import java.util.Random; public class Consumer2 extends Thread { static Random rand = new Random(); public void run() { while (true) { String s = CommandList.get(); System.out.println("Consuming " + s); try {Thread.sleep(rand.nextInt(1000)); } catch (InterruptedException e) { } } } }

Another test class import java.util.Random; public class CommandListTester2 { static Random rand = new Random(100); public static void main(String[] args) { Consumer consumer = new Consumer(); consumer.start(); String[] words = { "one", "two", "three", "four", "five", "six" }; for (int i = 0; i < words.length; i++) { CommandList.put(words[i]); try { Thread.sleep(rand.nextInt(1000)); } catch (InterruptedException e) { } } } }

The End