 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.

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.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
 2005 Pearson Education, Inc. All rights reserved Multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
 2006 Pearson Education, Inc. All rights reserved Multithreading.
1 L50 Multithreading (2). 2 OBJECTIVES  What producer/consumer relationships are and how they are implemented with multithreading.
Multithreading. Introduction Performing operations concurrently (in parallel) –We can walk, talk, breathe, see, hear, smell... all at the same time –Computers.
 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.
Definitions Process – An executing program
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
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.
© 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.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
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.
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 4 Outline 4.1 Introduction 4.2 Class Operations 4.3 Creating Class.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
111 © 2002, Cisco Systems, Inc. All rights reserved.
 2002 Prentice Hall, Inc. All rights reserved. Appendix H – Elevator Model Outline H.1 Introduction H.2 Class ElevatorModel H.3Classes Location and Floor.
 2002 Prentice Hall, Inc. All rights reserved. Introduction Concurrency normally available in OS primitives Java provides built-in multithreading –Multithreading.
Concurrent Programming and Threads Threads Blocking a User Interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
 2003 Prentice Hall, Inc. All rights reserved. Appendix E – Elevator Model Outline E.1 Introduction E.2 Class ElevatorSimulation E.3Classes Location and.
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.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading in JAVA
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 10.1 Test-Driving the Interest Calculator.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
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.
 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.
1 Mouse Events See Figure See Example in Figure 11.28,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 – Methods Part I.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 6 Outline 6.1 Introduction 6.2 Implementation: Visibility 6.3 Implementation:
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Concurrent Programming.
Java Thread Programming
Chapter 14 – Exception Handling
Multithreading / Concurrency
23 Multithreading.
Chapter 15 - Multithreading
Multithreading Chapter 23.
Multithreading.
Multithreading.
Threads in Java (Deitel & Deitel)
Chapter 4 - Control Structures: Part 1
Multithreading in java.
Threads and Multithreading
Threads in Java (Deitel & Deitel)
Chapter 15 – Exception Handling
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

 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 Priorities and Thread Scheduling 16.4 Creating and Executing Threads 16.5 Thread Synchronization 16.6 Producer/Consumer Relationship without Synchronization 16.7 Producer/Consumer Relationship with Synchronization 16.8 Producer/Consumer Relationship: Circular Buffer 16.9 Daemon Threads Runnable Interface (Optional Case Study) Thinking About Objects: Multithreading (Optional) Discovering Design Patterns: Concurrent Design Patterns

 2003 Prentice Hall, Inc. All rights reserved Introduction Concurrency normally available in OS primitives Java provides built-in multithreading –Multithreading improves the performance of some programs

 2003 Prentice Hall, Inc. All rights reserved Thread States: Life Cycle of a Thread Thread states –Born state Thread was just created –Ready state Thread’s start method invoked Thread can now execute –Running state Thread is assigned a processor and running –Dead state Thread has completed or exited Eventually disposed of by system

 2003 Prentice Hall, Inc. All rights reserved. Fig Thread life-cycle statechart diagram Ready Running BlockedSleepingWaiting start issue I/O request wait notify notifyAll timeout expires interrupt thread dispatch (assign a processor) quantum expiration yield sleep complete sleep interval expires interrupt Born enter synchronized statement I/O completes acquire lock interrupt When a thread completes (returns from its run method), it reaches the Dead state (shown here as the final state)

 2003 Prentice Hall, Inc. All rights reserved Thread Priorities and Thread Scheduling Java thread priority –Priority in range 1-10 Timeslicing –Each thread assigned time on the processor (called a quantum) –Keeps highest priority threads running

 2003 Prentice Hall, Inc. All rights reserved. Fig Thread priority scheduling example Priority 9 Priority 8 Priority 7 Priority 10 Priority 6 Priority 5 Priority 4 Priority 3 Priority 2 Priority 1 AB D C EF G H I JK Ready threads Thread.MIN_PRIORITY Thread.MAX_PRIORITY Thread.NORM_PRIORITY

 2003 Prentice Hall, Inc. All rights reserved Creating and Executing Threads Sleep state –Thread method sleep called –Thread sleeps for a set time interval then awakens

 2003 Prentice Hall, Inc. All rights reserved. Outline ThreadTester.ja va Lines 9-11 Lines // Fig. 16.3: ThreadTester.java 2 // Multiple threads printing at different intervals. 3 4 public class ThreadTester { 5 6 public static void main( String [] args ) 7 { 8 // create and name each thread 9 PrintThread thread1 = new PrintThread( "thread1" ); 10 PrintThread thread2 = new PrintThread( "thread2" ); 11 PrintThread thread3 = new PrintThread( "thread3" ); System.err.println( "Starting threads" ); thread1.start(); // start thread1 and place it in ready state 16 thread2.start(); // start thread2 and place it in ready state 17 thread3.start(); // start thread3 and place it in ready state System.err.println( "Threads started, main ends\n" ); } // end main } // end class ThreadTester 24 create four PrintThread s call start methods

 2003 Prentice Hall, Inc. All rights reserved. Outline ThreadTester.ja va Line 26 Line 35 Line // class PrintThread controls thread execution 26 class PrintThread extends Thread { 27 private int sleepTime; // assign name to thread by calling superclass constructor 30 public PrintThread( String name ) 31 { 32 super( name ); // pick random sleep time between 0 and 5 seconds 35 sleepTime = ( int ) ( Math.random() * 5001 ); 36 } // method run is the code to be executed by new thread 39 public void run() 40 { 41 // put thread to sleep for sleepTime amount of time 42 try { 43 System.err.println( 44 getName() + " going to sleep for " + sleepTime ); Thread.sleep( sleepTime ); 47 } 48 PrintThread extends Thread Constructor initializes sleepTime When the thread enters the running state, run is called

 2003 Prentice Hall, Inc. All rights reserved. Outline ThreadTester.ja va 49 // if thread interrupted during sleep, print stack trace 50 catch ( InterruptedException exception ) { 51 exception.printStackTrace(); 52 } // print thread name 55 System.err.println( getName() + " done sleeping" ); } // end method run } // end class PrintThread Starting threads Threads started, main ends thread1 going to sleep for 1217 thread2 going to sleep for 3989 thread3 going to sleep for 662 thread3 done sleeping thread1 done sleeping thread2 done sleeping

 2003 Prentice Hall, Inc. All rights reserved. Outline ThreadTester.ja va Starting threads thread1 going to sleep for 314 thread2 going to sleep for 1990 Threads started, main ends thread3 going to sleep for 3016 thread1 done sleeping thread2 done sleeping thread3 done sleeping

 2003 Prentice Hall, Inc. All rights reserved Thread Synchronization Java uses monitors for thread synchronization The sychronized keyword –Every synchronized method of an object has a monitor –One thread inside a synchronized method at a time –All other threads block until method finishes –Next highest priority thread runs when method finishes

 2003 Prentice Hall, Inc. All rights reserved Producer/Consumer Relationship without Synchronization Buffer –Shared memory region Producer thread –Generates data to add to buffer –Calls wait if consumer has not read previous message in buffer –Writes to empty buffer and calls notify for consumer Consumer thread –Reads data from buffer –Calls wait if buffer empty Synchronize threads to avoid corrupted data

 2003 Prentice Hall, Inc. All rights reserved. Outline Buffer.java 1 // Fig. 16.4: Buffer.java 2 // Buffer interface specifies methods called by Producer and Consumer. 3 4 public interface Buffer { 5 public void set( int value ); // place value into Buffer 6 public int get(); // return value from Buffer 7 }

 2003 Prentice Hall, Inc. All rights reserved. Outline Producer.java Line 5 Line 6 Line 16 Lines // Fig. 16.5: Producer.java 2 // Producer's run method controls a thread that 3 // stores values from 1 to 4 in sharedLocation. 4 5 public class Producer extends Thread { 6 private Buffer sharedLocation; // reference to shared object 7 8 // constructor 9 public Producer( Buffer shared ) 10 { 11 super( "Producer" ); 12 sharedLocation = shared; 13 } // store values from 1 to 4 in sharedLocation 16 public void run() 17 { 18 for ( int count = 1; count <= 4; count++ ) { // sleep 0 to 3 seconds, then place value in Buffer 21 try { 22 Thread.sleep( ( int ) ( Math.random() * 3001 ) ); 23 sharedLocation.set( count ); 24 } 25 Producer extends Thread This is a shared object Method run is overriddenThe thread goes to sleep, then the buffer is set

 2003 Prentice Hall, Inc. All rights reserved. Outline Producer.java 26 // if sleeping thread interrupted, print stack trace 27 catch ( InterruptedException exception ) { 28 exception.printStackTrace(); 29 } } // end for System.err.println( getName() + " done producing." + 34 "\nTerminating " + getName() + "."); } // end method run } // end class Producer

 2003 Prentice Hall, Inc. All rights reserved. Outline Consumer.java Line 5 Line 6 Line 16 Lines // Fig. 16.6: Consumer.java 2 // Consumer's run method controls a thread that loops four 3 // times and reads a value from sharedLocation each time. 4 5 public class Consumer extends Thread { 6 private Buffer sharedLocation; // reference to shared object 7 8 // constructor 9 public Consumer( Buffer shared ) 10 { 11 super( "Consumer" ); 12 sharedLocation = shared; 13 } // read sharedLocation's value four times and sum the values 16 public void run() 17 { 18 int sum = 0; for ( int count = 1; count <= 4; count++ ) { // sleep 0 to 3 seconds, read value from Buffer and add to sum 23 try { 24 Thread.sleep( ( int ) ( Math.random() * 3001 ) ); 25 sum += sharedLocation.get(); 26 } 27 Consumer extends Thread This is a shared object Method run is overriddenThe thread goes to sleep, then the buffer is read

 2003 Prentice Hall, Inc. All rights reserved. Outline Consumer.java 28 // if sleeping thread interrupted, print stack trace 29 catch ( InterruptedException exception ) { 30 exception.printStackTrace(); 31 } 32 } System.err.println( getName() + " read values totaling: " + sum + 35 ".\nTerminating " + getName() + "."); } // end method run } // end class Consumer

 2003 Prentice Hall, Inc. All rights reserved. Outline UnsynchronizedB uffer.java Line 4 Line 5 Lines 8 and 13 Lines 17 and 22 1 // Fig. 16.7: UnsynchronizedBuffer.java 2 // UnsynchronizedBuffer represents a single shared integer. 3 4 public class UnsynchronizedBuffer implements Buffer { 5 private int buffer = -1; // shared by producer and consumer threads 6 7 // place value into buffer 8 public void set( int value ) 9 { 10 System.err.println( Thread.currentThread().getName() + 11 " writes " + value ); buffer = value; 14 } // return value from buffer 17 public int get() 18 { 19 System.err.println( Thread.currentThread().getName() + 20 " reads " + buffer ); return buffer; 23 } } // end class UnsynchronizedBuffer This class implements the Buffer interface The data is a single integer This method sets the value in the buffer This method reads the value in the buffer

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t.java Line 9 Lines Lines // Fig. 16.8: SharedBufferTest.java 2 // SharedBufferTest creates producer and consumer threads. 3 4 public class SharedBufferTest { 5 6 public static void main( String [] args ) 7 { 8 // create shared object used by threads 9 Buffer sharedLocation = new UnsynchronizedBuffer(); // create producer and consumer objects 12 Producer producer = new Producer( sharedLocation ); 13 Consumer consumer = new Consumer( sharedLocation ); producer.start(); // start producer thread 16 consumer.start(); // start consumer thread } // end main } // end class SharedCell Create a Buffer objectCreate a Producer and a Consumer Start the Producer and Consumer threads

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t.java Consumer reads -1 Producer writes 1 Consumer reads 1 Consumer read values totaling: 2. Terminating Consumer. Producer writes 2 Producer writes 3 Producer writes 4 Producer done producing. Terminating Producer. Producer writes 1 Producer writes 2 Consumer reads 2 Producer writes 3 Consumer reads 3 Producer writes 4 Producer done producing. Terminating Producer. Consumer reads 4 Consumer read values totaling: 13. Terminating Consumer.

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t.java Producer writes 1 Consumer reads 1 Producer writes 2 Consumer reads 2 Producer writes 3 Consumer reads 3 Producer writes 4 Producer done producing. Terminating Producer. Consumer reads 4 Consumer read values totaling: 10. Terminating Consumer.

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

 2003 Prentice Hall, Inc. All rights reserved. Outline SynchronizedBuf fer.java Line 4 Line 6 Line 9 Line 12 Lines 15 and 21 1 // Fig. 16.9: SynchronizedBuffer.java 2 // SynchronizedBuffer synchronizes access to a single shared integer. 3 4 public class SynchronizedBuffer implements Buffer { 5 private int buffer = -1; // shared by producer and consumer threads 6 private int occupiedBufferCount = 0; // count of occupied buffers 7 8 // place value into buffer 9 public synchronized void set( int value ) 10 { 11 // for output purposes, get name of thread that called this method 12 String name = Thread.currentThread().getName(); // while there are no empty locations, place thread in waiting state 15 while ( occupiedBufferCount == 1 ) { // output thread information and buffer information, then wait 18 try { 19 System.err.println( name + " tries to write." ); 20 displayState( "Buffer full. " + name + " waits." ); 21 wait(); 22 } // if waiting thread interrupted, print stack trace 25 catch ( InterruptedException exception ) { 26 exception.printStackTrace(); 27 } This class implements the Buffer interface Remember the number of filled spaces Get the name of the thread Wait while the buffer is filled Method set is declared synchronized

 2003 Prentice Hall, Inc. All rights reserved. Outline SynchronizedBuf fer.java Line 31 Line 35 Line 39 Line 44 Line } // end while buffer = value; // set new buffer value // indicate producer cannot store another value 34 // until consumer retrieves current buffer value 35 ++occupiedBufferCount; displayState( name + " writes " + buffer ); notify(); // tell waiting thread to enter ready state } // end method set; releases lock on SynchronizedBuffer // return value from buffer 44 public synchronized int get() 45 { 46 // for output purposes, get name of thread that called this method 47 String name = Thread.currentThread().getName(); 48 Write to the bufferIncrement the buffer countAlert a waiting threadGet the name of the threadMethod get is declared synchronized

 2003 Prentice Hall, Inc. All rights reserved. Outline SynchronizedBuf fer.java Lines 50 and 56 Line 68 Line 72 Line // while no data to read, place thread in waiting state 50 while ( occupiedBufferCount == 0 ) { // output thread information and buffer information, then wait 53 try { 54 System.err.println( name + " tries to read." ); 55 displayState( "Buffer empty. " + name + " waits." ); 56 wait(); 57 } // if waiting thread interrupted, print stack trace 60 catch ( InterruptedException exception ) { 61 exception.printStackTrace(); 62 } } // end while // indicate that producer can store another value 67 // because consumer just retrieved buffer value 68 --occupiedBufferCount; displayState( name + " reads " + buffer ); notify(); // tell waiting thread to become ready to execute return buffer; Wait while the buffer is empty Decrement the buffer countAlert a waiting threadReturn the buffer

 2003 Prentice Hall, Inc. All rights reserved. Outline SynchronizedBuf fer.java } // end method get; releases lock on SynchronizedBuffer // display current operation and buffer state 79 public void displayState( String operation ) 80 { 81 StringBuffer outputLine = new StringBuffer( operation ); 82 outputLine.setLength( 40 ); 83 outputLine.append( buffer + "\t\t" + occupiedBufferCount ); 84 System.err.println( outputLine ); 85 System.err.println(); 86 } } // end class SynchronizedBuffer

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t2.java Line 11 Line 19 Lines // Fig : SharedBufferTest2.java 2 // SharedBufferTest2creates producer and consumer threads. 3 4 public class SharedBufferTest2 { 5 6 public static void main( String [] args ) 7 { 8 // create shared object used by threads; we use a SynchronizedBuffer 9 // reference rather than a Buffer reference so we can invoke 10 // SynchronizedBuffer method displayState from main 11 SynchronizedBuffer sharedLocation = new SynchronizedBuffer(); // Display column heads for output 14 StringBuffer columnHeads = new StringBuffer( "Operation" ); 15 columnHeads.setLength( 40 ); 16 columnHeads.append( "Buffer\t\tOccupied Count" ); 17 System.err.println( columnHeads ); 18 System.err.println(); 19 sharedLocation.displayState( "Initial State" ); // create producer and consumer objects 22 Producer producer = new Producer( sharedLocation ); 23 Consumer consumer = new Consumer( sharedLocation ); 24 Create a Buffer objectOutput initial stateCreate a Producer and a Consumer

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t2.java Lines producer.start(); // start producer thread 26 consumer.start(); // start consumer thread } // end main } // end class SharedBufferTest2 Operation Buffer Occupied Count Initial State -1 0 Consumer tries to read. Buffer empty. Consumer waits Producer writes Consumer reads Consumer tries to read. Buffer empty. Consumer waits. 1 0 Producer writes Consumer reads Producer writes Start the Producer and Consumer threads

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t2.java Consumer reads Consumer tries to read. Buffer empty. Consumer waits. 3 0 Producer writes Consumer reads Producer done producing. Terminating Producer. Consumer read values totaling: 10. Terminating Consumer. Operation Buffer Occupied Count Initial State -1 0 Consumer tries to read. Buffer empty. Consumer waits Producer writes Consumer reads Producer writes 2 2 1

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t2.java Producer tries to write. Buffer full. Producer waits. 2 1 Consumer reads Producer writes Consumer reads Producer writes Producer done producing. Terminating Producer. Consumer reads Consumer read values totaling: 10. Terminating Consumer. Operation Buffer Occupied Count Initial State -1 0 Producer writes Consumer reads Producer writes 2 2 1

 2003 Prentice Hall, Inc. All rights reserved. Outline SharedBufferTes t2.java Consumer reads Producer writes Consumer reads Producer writes Producer done producing. Terminating Producer. Consumer reads Consumer read values totaling: 10. Terminating Consumer.

 2003 Prentice Hall, Inc. All rights reserved Producer/Consumer Relationship: Circular Buffer Circular buffer –Multiple memory cells –Produce item if one or more empty cells –Consume item if one or more filled cells

 2003 Prentice Hall, Inc. All rights reserved. Outline RunnableOutput. java Line 5 Line 17 1 // Fig : RunnableOutput.java 2 // Class RunnableOutput updates JTextArea with output 3 import javax.swing.*; 4 5 public class RunnableOutput implements Runnable { 6 private JTextArea outputArea; 7 private String messageToAppend; 8 9 // initialize outputArea and message 10 public RunnableOutput( JTextArea output, String message ) 11 { 12 outputArea = output; 13 messageToAppend = message; 14 } // method called by SwingUtilities.invokeLater to update outputArea 17 public void run() 18 { 19 outputArea.append( messageToAppend ); 20 } } // end class RunnableOutput This class implements the Runnable interface Declare method run

 2003 Prentice Hall, Inc. All rights reserved. Outline Producer.java Lines 21 and 26 1 // Fig : Producer.java 2 // Producer’s run method controls a thread that 3 // stores values from 11 to 20 in sharedLocation. 4 import javax.swing.*; 5 6 public class Producer extends Thread { 7 private Buffer sharedLocation; 8 private JTextArea outputArea; 9 10 // constructor 11 public Producer( Buffer shared, JTextArea output ) 12 { 13 super( "Producer" ); 14 sharedLocation = shared; 15 outputArea = output; 16 } // store values from and in sharedLocation's buffer 19 public void run() 20 { 21 for ( int count = 11; count <= 20; count ++ ) { // sleep 0 to 3 seconds, then place value in Buffer 24 try { 25 Thread.sleep( ( int ) ( Math.random() * 3000 ) ); 26 sharedLocation.set( count ); 27 } Write the values from 11 to 20 to the buffer

 2003 Prentice Hall, Inc. All rights reserved. Outline Producer.java Lines // if sleeping thread interrupted, print stack trace 30 catch ( InterruptedException exception ) { 31 exception.printStackTrace(); 32 } 33 } String name = getName(); 36 SwingUtilities.invokeLater( new RunnableOutput( outputArea, "\n" + 37 name + " done producing.\n" + name + " terminated.\n" ) ); } // end method run } // end class Producer Update the output

 2003 Prentice Hall, Inc. All rights reserved. Outline Consumer.java 1 // Fig : Consumer.java 2 // Consumer’s run method controls a thread that loops ten 3 // times and reads a value from sharedLocation each time. 4 import javax.swing.*; 5 6 public class Consumer extends Thread { 7 private Buffer sharedLocation; // reference to shared object 8 private JTextArea outputArea; 9 10 // constructor 11 public Consumer( Buffer shared, JTextArea output ) 12 { 13 super( "Consumer" ); 14 sharedLocation = shared; 15 outputArea = output; 16 } // read sharedLocation's value ten times and sum the values 19 public void run() 20 { 21 int sum = 0; for ( int count = 1; count <= 10; count++ ) { 24

 2003 Prentice Hall, Inc. All rights reserved. Outline Consumer.java Line 28 Lines // sleep 0 to 3 seconds, read value from Buffer and add to sum 26 try { 27 Thread.sleep( ( int ) ( Math.random() * 3001 ) ); 28 sum += sharedLocation.get(); 29 } // if sleeping thread interrupted, print stack trace 32 catch ( InterruptedException exception ) { 33 exception.printStackTrace(); 34 } 35 } String name = getName(); 38 SwingUtilities.invokeLater( new RunnableOutput( outputArea, 39 "\nTotal " + name + " consumed: " + sum + ".\n" + 40 name + " terminated.\n ") ); } // end method run } // end class Consumer Read the value from the buffer Update the output

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBuffer. java Line 8 Line 11 Line 14 1 // Fig : CircularBuffer.java 2 // CircularBuffer synchronizes access to an array of shared buffers. 3 import javax.swing.*; 4 5 public class CircularBuffer implements Buffer { 6 7 // each array element is a buffer 8 private int buffers[] = { -1, -1, -1 }; 9 10 // occupiedBufferCount maintains count of occupied buffers 11 private int occupiedBufferCount = 0; // variables that maintain read and write buffer locations 14 private int readLocation = 0, writeLocation = 0; // reference to GUI component that displays output 17 private JTextArea outputArea; // constructor 20 public CircularBuffer( JTextArea output ) 21 { 22 outputArea = output; 23 } 24 The data is an array of three integers Remember the number of filled spaces Remember the read and write positions

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBuffer. java Line 26 Line 32 Lines Line // place value into buffer 26 public synchronized void set( int value ) 27 { 28 // for output purposes, get name of thread that called this method 29 String name = Thread.currentThread().getName(); // while there are no empty locations, place thread in waiting state 32 while ( occupiedBufferCount == buffers.length ) { // output thread information and buffer information, then wait 35 try { 36 SwingUtilities.invokeLater( new RunnableOutput( outputArea, 37 "\nAll buffers full. " + name + " waits." ) ); 38 wait(); 39 } // if waiting thread interrupted, print stack trace 42 catch ( InterruptedException exception ) 43 { 44 exception.printStackTrace(); 45 } } // end while // place value in writeLocation of buffers 50 buffers[ writeLocation ] = value; 51 Method set is declared synchronized Check if the buffer is full Update the output Write to the buffer

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBuffer. java Lines Line 57 Line 60 Lines Line 66 Line // update Swing GUI component with produced value 53 SwingUtilities.invokeLater( new RunnableOutput( outputArea, 54 "\n" + name + " writes " + buffers[ writeLocation ] + " ") ); // just produced a value, so increment number of occupied buffers 57 ++occupiedBufferCount; // update writeLocation for future write operation 60 writeLocation = ( writeLocation + 1 ) % buffers.length; // display contents of shared buffers 63 SwingUtilities.invokeLater( new RunnableOutput( 64 outputArea, createStateOutput() ) ); notify(); // return waiting thread (if there is one) to ready state } // end method set // return value from buffer 71 public synchronized int get() 72 { 73 // for output purposes, get name of thread that called this method 74 String name = Thread.currentThread().getName(); 75 Update the outputIncrement the buffer countUpdate the write locationUpdate the outputAlert a waiting threadMethod get is declared synchronized

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBuffer. java Line 77 Lines Line 94 Lines Line // while no data to read, place thread in waiting state 77 while ( occupiedBufferCount == 0 ) { // output thread information and buffer information, then wait 80 try { 81 SwingUtilities.invokeLater( new RunnableOutput( outputArea, 82 "\nAll buffers empty. " + name + " waits.") ); 83 wait(); 84 } // if waiting thread interrupted, print stack trace 87 catch ( InterruptedException exception ) { 88 exception.printStackTrace(); 89 } } // end while // obtain value at current readLocation 94 int readValue = buffers[ readLocation ]; // update Swing GUI component with consumed value 97 SwingUtilities.invokeLater( new RunnableOutput( outputArea, 98 "\n" + name + " reads " + readValue + " ") ); // just consumed a value, so decrement number of occupied buffers occupiedBufferCount; 102 Check if the buffer is empty Update the output Read a value from the bufferUpdate the outputDecrement the buffer count

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBuffer. java Line 104 Lines Line 110 Line // update readLocation for future read operation 104 readLocation = ( readLocation + 1 ) % buffers.length; // display contents of shared buffers 107 SwingUtilities.invokeLater( new RunnableOutput( 108 outputArea, createStateOutput() ) ); notify(); // return waiting thread (if there is one) to ready state return readValue; } // end method get // create state output 117 public String createStateOutput() 118 { 119 // first line of state information 120 String output = 121 "(buffers occupied: " + occupiedBufferCount + ")\nbuffers: "; for ( int i = 0; i < buffers.length; i++ ) 124 output += " " + buffers[ i ] + " "; // second line of state information 127 output += "\n "; 128 Update the read locationUpdate the outputAlert a waiting threadReturn a value from the buffer

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBuffer. java 129 for ( int i = 0; i < buffers.length; i++ ) 130 output += "---- "; // third line of state information 133 output += "\n "; // append readLocation (R) and writeLocation (W) 136 // indicators below appropriate buffer locations 137 for ( int i = 0; i < buffers.length; i++ ) if ( i == writeLocation && writeLocation == readLocation ) 140 output += " WR "; 141 else if ( i == writeLocation ) 142 output += " W "; 143 else if ( i == readLocation ) 144 output += " R "; 145 else 146 output += " "; output += "\n"; return output; } // end method createStateOutput } // end class CircularBuffer

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBufferT est.java Line 26 1 // Fig : CircularBufferTest.java 2 // CircularBufferTest shows two threads manipulating a circular buffer. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 // set up the producer and consumer threads and start them 8 public class CircularBufferTest extends JFrame { 9 JTextArea outputArea; // set up GUI 12 public CircularBufferTest() 13 { 14 super( "Demonstrating Thread Synchronizaton" ); outputArea = new JTextArea( 20,30 ); 17 outputArea.setFont( new Font( "Monospaced", Font.PLAIN, 12 ) ); 18 getContentPane().add( new JScrollPane( outputArea ) ); setSize( 310, 500 ); 21 setVisible( true ); // create shared object used by threads; we use a CircularBuffer 24 // reference rather than a Buffer reference so we can invoke 25 // CircularBuffer method createStateOutput 26 CircularBuffer sharedLocation = new CircularBuffer( outputArea ); 27 Create a Buffer object

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBufferT est.java Lines Lines Lines Line // display initial state of buffers in CircularBuffer 29 SwingUtilities.invokeLater( new RunnableOutput( outputArea, 30 sharedLocation.createStateOutput() ) ); // set up threads 33 Producer producer = new Producer( sharedLocation, outputArea ); 34 Consumer consumer = new Consumer( sharedLocation, outputArea ); producer.start(); // start producer thread 37 consumer.start(); // start consumer thread } // end constructor public static void main ( String args[] ) 42 { 43 CircularBufferTest application = new CircularBufferTest(); 44 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 45 } } // end class CirclularBufferTest Update the outputStart the Producer and Consumer threads Create a Producer and a Consumer Create an instance of this class

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBufferT est.java Value placed in last buffer. Next value will be deposited in first buffer.

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBufferT est.java Circular buffer effect—the fourth value is deposited in the first buffer. Value placed in last buffer. Next value will be deposited in first buffer. Circular buffer effect—the seventh value is deposited in the first buffer.

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBufferT est.java Value placed in last buffer. Next value will be deposited in first buffer. Circular buffer effect—the tenth value is deposited in the first buffer.

 2003 Prentice Hall, Inc. All rights reserved. Outline CircularBufferT est.java

 2003 Prentice Hall, Inc. All rights reserved Daemon Threads Run for benefit of other threads –Do not prevent program from terminating –Garbage collector is a daemon thread Set daemon thread with method setDaemon

 2003 Prentice Hall, Inc. All rights reserved Runnable Interface A class cannot extend more than one class Implement Runnable for multithreading support

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java 1 // Fig : RandomCharacters.java 2 // Class RandomCharacters demonstrates the Runnable interface 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class RandomCharacters extends JApplet implements ActionListener { 8 private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 9 private final static int SIZE = 3; 10 private JLabel outputs[]; 11 private JCheckBox checkboxes[]; 12 private Thread threads[]; 13 private boolean suspended[]; // set up GUI and arrays 16 public void init() 17 { 18 outputs = new JLabel[ SIZE ]; 19 checkboxes = new JCheckBox[ SIZE ]; 20 threads = new Thread[ SIZE ]; 21 suspended = new boolean[ SIZE ]; Container container = getContentPane(); 24 container.setLayout( new GridLayout( SIZE, 2, 5, 5 ) ); 25

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java Line 43 Lines Line // create GUI components, register listeners and attach 27 // components to content pane 28 for ( int count = 0; count < SIZE; count++ ) { 29 outputs[ count ] = new JLabel(); 30 outputs[ count ].setBackground( Color.GREEN ); 31 outputs[ count ].setOpaque( true ); 32 container.add( outputs[ count ] ); checkboxes[ count ] = new JCheckBox( "Suspended" ); 35 checkboxes[ count ].addActionListener( this ); 36 container.add( checkboxes[ count ] ); 37 } } // end method init // create and start threads each time start is called (i.e., after 42 // init and when user revists Web page containing this applet) 43 public void start() 44 { 45 for ( int count = 0; count < threads.length; count++ ) { // create Thread; initialize object that implements Runnable 48 threads[ count ] = 49 new Thread( new RunnableObject(), "Thread " + ( count + 1 ) ); threads[ count ].start(); // begin executing Thread 52 } Applet start methodCreate three Thread objects and initialize each with a RunnableObject Call thread start method

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java Line 66 Line 70 Line } // determine thread location in threads array 56 private int getIndex( Thread current ) 57 { 58 for ( int count = 0; count < threads.length; count++ ) 59 if ( current == threads[ count ] ) 60 return count; return -1; 63 } // called when user switches Web pages; stops all threads 66 public synchronized void stop() 67 { 68 // set references to null to terminate each thread's run method 69 for ( int count = 0; count < threads.length; count++ ) 70 threads[ count ] = null; notifyAll(); // notify all waiting threads, so they can terminate 73 } // handle button events 76 public synchronized void actionPerformed( ActionEvent event ) 77 { Method stop stops all threads Set thread references in array threads to null Invoke method notifyAll to ready waiting threads

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java Line 81 Line 89 Line 98 Line for ( int count = 0; count < checkboxes.length; count++ ) { if ( event.getSource() == checkboxes[ count ] ) { 81 suspended[ count ] = !suspended[ count ]; // change label color on suspend/resume 84 outputs[ count ].setBackground( 85 suspended[ count ] ? Color.RED : Color.GREEN ); // if thread resumed, make sure it starts executing 88 if ( !suspended[ count ] ) 89 notifyAll(); return; 92 } 93 } } // end method actionPerformed // private inner class that implements Runnable to control threads 98 private class RunnableObject implements Runnable { // place random characters in GUI, variables currentThread and 101 // index are final so can be used in an anonymous inner class 102 public void run() 103 { Toggle boolean value in array suspended Call notifyAll to start ready threads Class RunnableObject implements Runnable interface Declare method run

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java Line 112 Line 120 Line // get reference to executing thread 105 final Thread currentThread = Thread.currentThread(); // determine thread's position in array 108 final int index = getIndex( currentThread ); // loop condition determines when thread should stop; loop 111 // terminates when reference threads[ index ] becomes null 112 while ( threads[ index ] == currentThread ) { // sleep from 0 to 1 second 115 try { 116 Thread.sleep( ( int ) ( Math.random() * 1000 ) ); // determine whether thread should suspend execution; 119 // synchronize on RandomCharacters applet object 120 synchronized( RandomCharacters.this ) { while ( suspended[ index ] && 123 threads[ index ] == currentThread ) { // temporarily suspend thread execution 126 RandomCharacters.this.wait(); 127 } 128 } // end synchronized statement The while loop executes as long as the index of array threads equals currentThread The synchronized block helps suspend currently executing thread Invoke method wait on applet to place thread in waiting state

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java Line } // end try // if thread interrupted during wait/sleep, print stack trace 133 catch ( InterruptedException exception ) { 134 exception.printStackTrace(); 135 } // display character on corresponding JLabel 138 SwingUtilities.invokeLater( 139 new Runnable() { // pick random character and display it 142 public void run() 143 { 144 char displayChar = 145 alphabet.charAt( ( int ) ( Math.random() * 26 ) ); outputs[ index ].setText( 148 currentThread.getName() + ": " + displayChar ); 149 } } // end inner class ); // end call to SwingUtilities.invokeLater Anonymous inner class implements Runnable interface

 2003 Prentice Hall, Inc. All rights reserved. Outline RandomCharacter s.java } // end while System.err.println( currentThread.getName() + " terminating" ); } // end method run } // end private inner class RunnableObject } // end class RandomCharacters

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Multithreading Concurrent models –UML contains support for building concurrent models –Discus how simulation benefits from multithreading waitingPassenger must wait for ridingPassenger to exit Elevator Use synchronized method –Guarantees only one Person in Elevator at a time

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Multithreading Threads, Active Classes and Synchronized method –UML represents a thread as an active class Thick black border in UML diagram indicates an active class

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Multithreading Sequence Diagrams –Shows interactions among objects Shows messages passed among objects over time –Rectangle enclosing an object name represents that object Use same naming conventions as collaboration diagrams –Lifeline Dotted line running down from an object name Actions occur on lifeline in chronological order, top to bottom –Arrows Dashed arrows –Represent “return messages,” return of control to object Solid arrows –A message sent from one object to another

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Multithreading Class diagram now uses active classes –Elevator and Person are now active classes

 2003 Prentice Hall, Inc. All rights reserved. Fig Sequence diagram that models a Person requesting and entering an Elevator pressButton( ) openDoor( ) buttonPressed( ) elevatorArrived( ) floorDoor : Door [Elevator on opposite Floor of request] floorButton : Button elevatorDoor : ElevatorDoor elevator: Elevator [ !floorDoor.isDoorOpen() ] ElevatorShaft requestElevator( ) openDoor( ) *[ !floorDoor.isDoorOpen() ] wait( ) setLocation( elevator ) Sequence continues in Fig elevator travels to other floor Person

 2003 Prentice Hall, Inc. All rights reserved. Fig Sequence diagram that models a Person traveling in an Elevator pressButton( ) buttonPressed( ) elevatorArrived( ) elevatorDoor : ElevatorDoor elevatorButton : Button openDoor( ) *[ !elevatorDoor.isDoorOpen() ] wait( ) setLocation( elevator.getCurrentFloor() ) setMoving( true ) closeDoor( ) Sequence continued from Fig setMoving( false ) changeFloors() == 5 seconds Person : Elevator

 2003 Prentice Hall, Inc. All rights reserved. Fig Revised class diagram of the elevator simulation

 2003 Prentice Hall, Inc. All rights reserved. Fig Final class diagram with attributes and operations Light - lightOn : Boolean = false + turnOnLight( ) : void + turnOffLight( ) : void Bell + ringBell( ) : void ElevatorSimulation - numberOfPeople : Integer = 0 + addPerson( ) : void Button - pressed : Boolean = false + resetButton( ) : void + pressButton( ) : void Door - open : Boolean = false + openDoor( ) : void + closeDoor( ) : void Floor + getButton( ) : Button + getDoor( ) : Door Location - locationName : String # setLocationName( String ) : void + getLocationName( ) : String + getButton( ) : Button + getDoor( ) : Door Elevator - moving : Boolean = false - summoned : Boolean = false - currentFloor : Location - destinationFloor : Location - travelTime : Integer = 5 + ride( ) : void + requestElevator( ) : void – setMoving( Boolean ) : void + getButton( ) : Button + getDoor( ) : Door + getLocation( ) : Location Person - ID : Integer - moving : Boolean = true - location : Location - maxTravelTime : Integer = 10 * 60 + doorOpened( ) : void

 2003 Prentice Hall, Inc. All rights reserved (Optional) Discovering Design Patterns: Concurrent Design Patterns Concurrency Design Patterns –Single-Threaded Execution design pattern Stops several threads from invoking a method concurrently –Guarded Suspension design pattern Suspends and resumes a threads activity when a condition met –Balking design pattern Causes method to balk if an object occupies a certain state –Read/Write Lock design pattern Multiple read on an object but exclusive write –Two-Phase Termination design pattern Uses two-phase termination process to ensure resources freed