0
Multi-threading U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd IADCS Diploma Course
What’s a Thread? <ul><li>A process is an executing program  </li></ul><ul><ul><ul><li>memory allocated by OS </li></ul></u...
Initial Remarks about Threads <ul><li>Cheaper in computing resources and creation , a thread can only act within a single ...
Some spesific uses for threads <ul><li>Long initiations  (in applets that take a while to initialize) </li></ul><ul><li>Re...
Multitasking vs. Multithreading <ul><li>Multitasking operating systems run multiple programs simultaneously. </li></ul><ul...
Overview of Multitasking <ul><li>Each of programs has at least one thread within it. </li></ul><ul><li>Single thread in a ...
Processes in a Multitasking Environment <ul><li>Data within processes is seperated; separate stack for local variables and...
Overview of Multithreading <ul><li>Analogy : thread   process </li></ul><ul><li>Multiple thread running within a single i...
Properties of Multiple Threads <ul><li>Each thread begins execution at a well-defined location. </li></ul><ul><li>Code exe...
Possible Uses for Multithreading <ul><li>In general, you’ll have some part of your program </li></ul><ul><li>tied to a par...
<ul><li>Class  Thread :  An Overview of the  Thread  Methods </li></ul><ul><li>Class  Thread  constructors public  Thread(...
3. Threaded States: Life Cycle of a Thread <ul><li>Thread states </li></ul><ul><ul><li>Born state </li></ul></ul><ul><ul><...
3. Thread States: Life Cycle of a Thread
4. Thread Priorities and Thread Scheduling <ul><li>Java thread priority </li></ul><ul><ul><li>Priority in range 1-10 </li>...
ThreadTester.java //ThreadTester.java public class  ThreadTester { // create and start threads public static void  main( S...
ThreadTester.java Lines 33-71 Lines 38-48 Lines 51-69 class  PrintThread  extends  Thread { private int  sleepTime; // Pri...
5. Thread Synchronization <ul><li>Java uses monitors for thread synchronization </li></ul><ul><li>The  sychronized  keywor...
6. Producer/Consumer Relationship without    Synchronization <ul><li>Buffer </li></ul><ul><ul><li>Shared memory region </l...
ProduceInteger.java Line 10 Lines 15-37 //ProduceInteger.java public class  ProduceInteger  extends  Thread { private  Hol...
ConsumeInteger.java Line 10 Lines 15-39 Line 23 Lines 31-32 //ConsumeInteger.java public class  ConsumeInteger  extends  T...
HoldIntegerUnsynchronized.java Line 4 Lines 7-13 Lines 16-22 // HoldIntegerUnsynchronized.java // Definition of class Hold...
SharedCell.java Lines 6-20 //SharedCell.java // Show multiple threads modifying shared object. public class  SharedCell { ...
7. Producer/Consumer Relationship with    Thread Synchronization <ul><li>Synchronize threads to ensure correct data </li><...
ProduceInteger.java Line 10 Lines 15-37 // ProduceInteger.java // Definition of threaded class ProduceInteger public class...
// ConsumeInteger.java // Definition of threaded class ConsumeInteger public class  ConsumeInteger  extends  Thread { priv...
HoldIntegerSynchronized.java Line 6 Line 7 Lines 12-39 Line 14 // HoldIntegerSynchronized.java // Definition of class Hold...
HoldIntegerSynchronized.java Lines 44-70 Line 46 writeable =  false ; // tell a waiting thread to become ready notify();  ...
SharedCell.java Lines 6-20 // SharedCell.java // Show multiple threads modifying shared object. public class  SharedCell {...
Program Output ProduceInteger setting sharedInt to 1 ConsumeInteger retrieving sharedInt value 1 ProduceInteger setting sh...
8. Producer/Consumer Relationship:    The Circular Buffer <ul><li>Circular buffer </li></ul><ul><ul><li>Multiple memory ce...
UpdateThread.java Lines 7-24 Lines 19-22 // UpdateThread.java // Class for updating JTextArea with output. // Java extensi...
ProduceInteger.java Line 9 // ProduceInteger.java import  javax.swing.*; public class  ProduceInteger  extends  Thread { p...
//ConsumeInteger.java import  javax.swing.*; public class  ConsumeInteger  extends  Thread { private  HoldIntegerSynchroni...
//SharedCell.java // Show multiple threads modifying shared object. import  java.awt.*; import  java.awt.event.*; import  ...
Program Output
9. Daemon Threads <ul><li>Runs for benefit of other threads </li></ul><ul><ul><li>Do not prevent program from terminating ...
Upcoming SlideShare
Loading in...5
×

Multithreading

2,434

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,434
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
207
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "Multithreading"

  1. 1. Multi-threading U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd IADCS Diploma Course
  2. 2. What’s a Thread? <ul><li>A process is an executing program </li></ul><ul><ul><ul><li>memory allocated by OS </li></ul></ul></ul><ul><ul><ul><li>usually no memory sharing between processes </li></ul></ul></ul><ul><li>A thread is a single sequential flow of control </li></ul><ul><ul><ul><li>runs in the address space of a process </li></ul></ul></ul><ul><ul><ul><li>has its own program counter and its own stack frame </li></ul></ul></ul><ul><li>A thread is a path of execution through a program . </li></ul><ul><li>Single threaded programs->one path of execution </li></ul><ul><li>Multiple threaded programs -> two or more </li></ul><ul><li>Threads run in methods or constructors. The threads go into the methods and follow their instructions. </li></ul>1. Introduction
  3. 3. Initial Remarks about Threads <ul><li>Cheaper in computing resources and creation , a thread can only act within a single process. </li></ul><ul><li>Java threads are built into the language Threads are &quot;light-weight&quot; processes (unlike UNIX processes), which communicate by a combination of shared memory and message passing . </li></ul><ul><li>Sharing resources between threads is done with synchronization. </li></ul><ul><li>This communication mechanism is employed naturally by Java </li></ul><ul><li>Java threads are based on a locking mechanism using monitors for synchronization </li></ul>1. Introduction (cont;)
  4. 4. Some spesific uses for threads <ul><li>Long initiations (in applets that take a while to initialize) </li></ul><ul><li>Repetitive or timed tasks (animations) </li></ul><ul><li>Asynchronous events (event handling such as a mouse click) </li></ul><ul><li>Multiple Tasks (To do more than one thing at once) </li></ul><ul><li>Java applications and applets are naturally threaded . </li></ul>1. Introduction (cont;)
  5. 5. Multitasking vs. Multithreading <ul><li>Multitasking operating systems run multiple programs simultaneously. </li></ul><ul><li>O.S is reponsible for splitting time the time among the different programs that are running </li></ul><ul><li>Once systems allowed different users to run programs at the same time it was a short step to letting the same user run multiple programs simultaneously . </li></ul><ul><li>Multithreading enables users and programs to accomplish multiple simultaneous tasks. </li></ul>1. Introduction (cont;)
  6. 6. Overview of Multitasking <ul><li>Each of programs has at least one thread within it. </li></ul><ul><li>Single thread in a single process </li></ul><ul><li>Process begins execution at a well-known point. </li></ul><ul><li>(i.e main () ) </li></ul><ul><li>Execution of statements follow a predefined order. </li></ul><ul><li>During execution process has access to certain data: thread’s stack->local variables </li></ul><ul><li> object references->instance variables </li></ul><ul><li>class or object references-> static variables </li></ul>1. Introduction (cont;)
  7. 7. Processes in a Multitasking Environment <ul><li>Data within processes is seperated; separate stack for local variables and data area for objects </li></ul>1. Introduction (cont;)
  8. 8. Overview of Multithreading <ul><li>Analogy : thread  process </li></ul><ul><li>Multiple thread running within a single instance of JVM  multiple processes within an OS </li></ul>1. Introduction (cont;)
  9. 9. Properties of Multiple Threads <ul><li>Each thread begins execution at a well-defined location. </li></ul><ul><li>Code execution from starting location in a predefined sequence. </li></ul><ul><li>Each thread executes code independently of others in the prg. </li></ul><ul><li>Also mechanisms of threads that allow cooperation. </li></ul><ul><li>The threads appear to have a certain degree of simultaneous execution. </li></ul><ul><li>Access to various types of data </li></ul><ul><li>Each thread is separate, so that local variables in the methods are seperate. </li></ul><ul><li>Objects and their instance variables can be shared btw threads in a Java program . </li></ul><ul><li>Static variables are automatically shared . </li></ul>1. Introduction (cont;)
  10. 10. Possible Uses for Multithreading <ul><li>In general, you’ll have some part of your program </li></ul><ul><li>tied to a particular event or resource (and you don’t want to hang up the rest of your program because of that). </li></ul><ul><li>So you create a thread associated with that event or resource and let it run independently of the main program. </li></ul><ul><li>A good example could be a “quit” button </li></ul><ul><ul><li>you don’t want to be forced to poll the quit button in every piece of code you write in your program and yet you want the quit button to be responsive, as if you were checking it regularly. </li></ul></ul><ul><li>In fact, one of the most immediately compelling reasons for multithreading is to produce a responsive user interface. </li></ul>1. Introduction (cont;)
  11. 11. <ul><li>Class Thread : An Overview of the Thread Methods </li></ul><ul><li>Class Thread constructors public Thread( String threadName ) public Thread() </li></ul><ul><li>Code for thread in thread’s run method </li></ul><ul><li>Method sleep makes thread inactive </li></ul><ul><li>Method interrupt interrupts a running thread </li></ul><ul><li>Method isAlive checks status of a thread </li></ul><ul><li>Method setName sets a thread’s name </li></ul><ul><li>Method join </li></ul><ul><ul><li>Waits for thread to finish and continues from current thread </li></ul></ul>
  12. 12. 3. Threaded States: Life Cycle of a Thread <ul><li>Thread states </li></ul><ul><ul><li>Born state </li></ul></ul><ul><ul><ul><li>Thread was just created </li></ul></ul></ul><ul><ul><li>Ready state </li></ul></ul><ul><ul><ul><li>Thread’s start method invoked </li></ul></ul></ul><ul><ul><ul><li>Thread can now execute </li></ul></ul></ul><ul><ul><li>Running state </li></ul></ul><ul><ul><ul><li>Thread is assigned a processor and running </li></ul></ul></ul><ul><ul><li>Dead state </li></ul></ul><ul><ul><ul><li>Thread has completed or exited </li></ul></ul></ul><ul><ul><ul><li>Eventually disposed of by system </li></ul></ul></ul>
  13. 13. 3. Thread States: Life Cycle of a Thread
  14. 14. 4. Thread Priorities and Thread Scheduling <ul><li>Java thread priority </li></ul><ul><ul><li>Priority in range 1-10 </li></ul></ul><ul><li>Timeslicing </li></ul><ul><ul><li>Each thread assigned time on the processor by quantum </li></ul></ul><ul><ul><li>Keeps highest priority threads running </li></ul></ul><ul><li>One can implement threads in two ways: </li></ul><ul><ul><ul><ul><ul><li>First, by subclassing the Thread class </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Second, by implementing the Runnable interface </li></ul></ul></ul></ul></ul><ul><li>The Runnable interface allows you to add threading to a class which cannot conveniently extend Thread. </li></ul><ul><li>A class that implements the Runnable interface (including the Thread class itself) must implement the run() method containing the &quot;body&quot; of the thread. </li></ul>
  15. 15. ThreadTester.java //ThreadTester.java public class ThreadTester { // create and start threads public static void main( String args[] ) { PrintThread thread1, thread2, thread3, thread4; // create four PrintThread objects thread1 = new PrintThread( &quot;thread1&quot; ); thread2 = new PrintThread( &quot;thread2&quot; ); thread3 = new PrintThread( &quot;thread3&quot; ); thread4 = new PrintThread( &quot;thread4&quot; ); System.err.println( &quot; Starting threads&quot; ); // start executing PrintThreads thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.err.println( &quot;Threads started &quot; ); } } // end class ThreadTester Class ThreadTester creates four PrintThread s and calls their start methods
  16. 16. ThreadTester.java Lines 33-71 Lines 38-48 Lines 51-69 class PrintThread extends Thread { private int sleepTime; // PrintThread constructor assigns name to thread // by calling superclass Thread constructor public PrintThread( String name ) { super ( name ); // sleep between 0 and 5 seconds sleepTime = ( int ) ( Math.random() * 5000 ); // display name and sleepTime System.err.println( &quot;Name: &quot; + getName() + &quot;; sleep: &quot; + sleepTime ); } // control thread's execution public void run() { // put thread to sleep for a random interval try { System.err.println( getName() + &quot; going to sleep&quot; ); // put thread to sleep Thread.sleep( sleepTime ); } Thread run method prints a String saying the thread is going to sleep and thread sleeps // if thread interrupted during sleep, catch exception // and display error message catch ( InterruptedException interruptedException ) { System.err.println( interruptedException.toString() ); } // print thread name System.err.println( getName() + &quot; done sleeping&quot; ); } } // end class PrintThread Thread prints name when done sleeping PrintThread inherits from Thread so each object of the class can execute in parallel Constructor initializes sleepTime to be 0 to 4.999 seconds and outputs name and value of sleepTime
  17. 17. 5. Thread Synchronization <ul><li>Java uses monitors for thread synchronization </li></ul><ul><li>The sychronized keyword </li></ul><ul><ul><li>Every synchronized method of an object has a monitor </li></ul></ul><ul><ul><li>One thread inside a synchronized method at a time </li></ul></ul><ul><ul><li>All other threads block until method finishes </li></ul></ul><ul><ul><li>Next highest priority thread runs when method finishes </li></ul></ul>
  18. 18. 6. Producer/Consumer Relationship without Synchronization <ul><li>Buffer </li></ul><ul><ul><li>Shared memory region </li></ul></ul><ul><li>Producer thread </li></ul><ul><ul><li>Calls produce method to add item to buffer </li></ul></ul><ul><ul><li>Calls wait if consumer has not read last message in buffer </li></ul></ul><ul><ul><li>Writes to empty buffer and calls notify for consumer </li></ul></ul><ul><li>Consumer thread </li></ul><ul><ul><li>Reads message from buffer </li></ul></ul><ul><ul><li>Calls wait if buffer empty </li></ul></ul><ul><li>Synchronize threads to avoid corrupted data </li></ul>
  19. 19. ProduceInteger.java Line 10 Lines 15-37 //ProduceInteger.java public class ProduceInteger extends Thread { private HoldIntegerUnsynchronized sharedObject; // initialize ProduceInteger thread object public ProduceInteger( HoldIntegerUnsynchronized shared ) { super ( &quot;ProduceInteger&quot; ); sharedObject = shared; } // ProduceInteger thread loops 10 times and calls // sharedObject's setSharedInt method each time public void run() { for ( int count = 1 ; count <= 10 ; count++ ) { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } // call sharedObject method from this // thread of execution sharedObject.setSharedInt( count ); } Method run loops 10 times, sleep ing 0-3 seconds and calling setSharedInt System.err.println( getName() + &quot; finished producing values&quot; + &quot; Terminating &quot; + getName() ); } } // end class ProduceInteger Thread prints that it finished Instance variable sharedObject refers to object shared
  20. 20. ConsumeInteger.java Line 10 Lines 15-39 Line 23 Lines 31-32 //ConsumeInteger.java public class ConsumeInteger extends Thread { private HoldIntegerUnsynchronized sharedObject; // initialize ConsumerInteger thread object public ConsumeInteger( HoldIntegerUnsynchronized shared ) { super ( &quot;ConsumeInteger&quot; ); sharedObject = shared; } // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void run() { int value, sum = 0 ; do { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; } while ( value != 10 ); Each iteration causes the thread to sleep 0-3 seconds Call method getSharedInt and assign to variable sum System.err.println( getName() + &quot; retrieved values totaling: &quot; + sum + &quot; Terminating &quot; + getName() ); } } // end class ConsumeInteger Thread prints that it is done consuming Initializes sharedObject to refer to object shared Method run contains a do / while structure that loops 10 times
  21. 21. HoldIntegerUnsynchronized.java Line 4 Lines 7-13 Lines 16-22 // HoldIntegerUnsynchronized.java // Definition of class HoldIntegerUnsynchronized. public class HoldIntegerUnsynchronized { private int sharedInt = -1 ; // unsynchronized method to place value in sharedInt public void setSharedInt( int value ) { System.err.println( Thread.currentThread().getName() + &quot; setting sharedInt to &quot; + value ); sharedInt = value; } // unsynchronized method return sharedInt's value public int getSharedInt() { System.err.println( Thread.currentThread().getName() + &quot; retrieving sharedInt value &quot; + sharedInt ); return sharedInt; } } // end class HoldIntegerUnsynchronized Instance variable sharedInt is the shared buffer Method setSharedInt not synchronized Method getSharedInt not synchronized
  22. 22. SharedCell.java Lines 6-20 //SharedCell.java // Show multiple threads modifying shared object. public class SharedCell { // execute application public static void main( String args[] ) { HoldIntegerUnsynchronized sharedObject = new HoldIntegerUnsynchronized(); // create threads ProduceInteger producer = new ProduceInteger( sharedObject ); ConsumeInteger consumer = new ConsumeInteger( sharedObject ); // start threads producer.start(); consumer.start(); } } // end class SharedCell Method main creates a ProduceInteger thread and a ConsumeInteger thread and starts them
  23. 23. 7. Producer/Consumer Relationship with Thread Synchronization <ul><li>Synchronize threads to ensure correct data </li></ul>
  24. 24. ProduceInteger.java Line 10 Lines 15-37 // ProduceInteger.java // Definition of threaded class ProduceInteger public class ProduceInteger extends Thread { private HoldIntegerSynchronized sharedObject; // initialize ProduceInteger thread object public ProduceInteger( HoldIntegerSynchronized shared ) { super ( &quot;ProduceInteger&quot; ); sharedObject = shared; } // ProduceInteger thread loops 10 times and calls // sharedObject's setSharedInt method each time public void run() { for ( int count = 1 ; count <= 10 ; count++ ) { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } // call sharedObject method from this // thread of execution sharedObject.setSharedInt( count ); } Instance variable sharedObject refers to object shared Method run loops 10 times, sleep ing 0-3 seconds and calling setSharedInt System.err.println( getName() + &quot; finished producing values&quot; + &quot; Terminating &quot; + getName() ); } } // end class ProduceInteger Thread prints that it finished
  25. 25. // ConsumeInteger.java // Definition of threaded class ConsumeInteger public class ConsumeInteger extends Thread { private HoldIntegerSynchronized sharedObject; // initialize ConsumerInteger thread object public ConsumeInteger( HoldIntegerSynchronized shared ) { super ( &quot;ConsumeInteger&quot; ); sharedObject = shared; } // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void run() { int value, sum = 0 ; do { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; } while ( value != 10 ); System.err.println( getName() + &quot; retrieved values totaling: &quot; + sum + &quot; Terminating &quot; + getName() ); } } // end class ConsumeInteger Thread prints that it is done consuming 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
  26. 26. HoldIntegerSynchronized.java Line 6 Line 7 Lines 12-39 Line 14 // HoldIntegerSynchronized.java // Definition of class HoldIntegerSynchronized that // uses thread synchronization to ensure that both // threads access sharedInt at the proper times. public class HoldIntegerSynchronized { private int sharedInt = -1 ; private boolean writeable = true ; // condition variable // synchronized method allows only one thread at a time to // invoke this method to set the value for a particular // HoldIntegerSynchronized object public synchronized void setSharedInt( int value ) { while ( !writeable ) { // not the producer's turn // thread that called this method must wait try { wait(); } // process Interrupted exception while thread waiting catch ( InterruptedException exception ) { exception.printStackTrace(); } } System.err.println( Thread.currentThread().getName() + &quot; setting sharedInt to &quot; + value ); // set new sharedInt value sharedInt = value; Variable sharedInt represents the shared buffer Variable writeable is the monitor condition variable Method setSharedInt now synchronized Check if sharedInt can be written
  27. 27. HoldIntegerSynchronized.java Lines 44-70 Line 46 writeable = false ; // tell a waiting thread to become ready notify(); } // synchronized method allows only one thread at a time to // invoke this method to get the value for a particular // HoldIntegerSynchronized object public synchronized int getSharedInt() { while ( writeable ) { // not the consumer's turn // thread that called this method must wait try { wait(); } // process Interrupted exception while thread waiting catch ( InterruptedException exception ) { exception.printStackTrace(); } } // indicate that producer cant store another value // because a consumer just retrieved sharedInt value writeable = true ; // tell a waiting thread to become ready notify(); System.err.println( Thread.currentThread().getName() + &quot; retrieving sharedInt value &quot; + sharedInt ); Method getSharedInt now synchronized Check if sharedInt can be read return sharedInt; } } // end class HoldIntegerSynchronized
  28. 28. SharedCell.java Lines 6-20 // SharedCell.java // Show multiple threads modifying shared object. public class SharedCell { // execute application public static void main( String args[] ) { HoldIntegerSynchronized sharedObject = new HoldIntegerSynchronized(); // create threads ProduceInteger producer = new ProduceInteger( sharedObject ); ConsumeInteger consumer = new ConsumeInteger( sharedObject ); // start threads producer.start(); consumer.start(); } } // end class SharedCell Method main creates a ProduceInteger thread and a ConsumeInteger thread and starts them
  29. 29. 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
  30. 30. 8. Producer/Consumer Relationship: The Circular Buffer <ul><li>Circular buffer </li></ul><ul><ul><li>Multiple memory cells </li></ul></ul><ul><ul><li>Produce item if one or more empty cells </li></ul></ul><ul><ul><li>Consume item if one or more filled cells </li></ul></ul>
  31. 31. UpdateThread.java Lines 7-24 Lines 19-22 // UpdateThread.java // Class for updating JTextArea with output. // Java extension packages import javax.swing.*; public class UpdateThread extends Thread { private JTextArea outputArea; private String messageToOutput; // initialize outputArea and message public UpdateThread( JTextArea output, String message ) { outputArea = output; messageToOutput = message; } // method called to update outputArea public void run() { outputArea.append( messageToOutput ); } } // end class UpdateThread Class UpdateThread passed as a parameter to SwingUtilities method invokeLater to ensure GUI updates properly Method run appends text to outputArea
  32. 32. ProduceInteger.java Line 9 // ProduceInteger.java import javax.swing.*; public class ProduceInteger extends Thread { private HoldIntegerSynchronized sharedObject; private JTextArea outputArea; // initialize ProduceInteger public ProduceInteger( HoldIntegerSynchronized shared, JTextArea output ) { super ( &quot;ProduceInteger&quot; ); sharedObject = shared; outputArea = output; } // ProduceInteger thread loops 10 times and calls // sharedObject's setSharedInt method each time public void run() { for ( int count = 1 ; count <= 10 ; count++ ) { // sleep for a random interval // Note: Interval shortened purposely to fill buffer try { Thread.sleep( ( int ) ( Math.random() * 500 ) ); } Places output in JTextArea outputArea // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } sharedObject.setSharedInt( count ); } // update Swing GUI component SwingUtilities.invokeLater( new UpdateThread( outputArea, &quot; &quot; + getName() + &quot; finished producing values&quot; + &quot; Terminating &quot; + getName() + &quot; &quot; ) ); } } // end class ProduceInteger SwingUtilities method invokeLater ensures GUI updates properly
  33. 33. //ConsumeInteger.java import javax.swing.*; public class ConsumeInteger extends Thread { private HoldIntegerSynchronized sharedObject; private JTextArea outputArea; // initialize ConsumeInteger public ConsumeInteger( HoldIntegerSynchronized shared, JTextArea output ){ super ( &quot;ConsumeInteger&quot; ); sharedObject = shared; outputArea = output; } Places output in JTextArea outputArea // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void run() { int value, sum = 0; do { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; } while ( value != 10 ); // update Swing GUI component SwingUtilities.invokeLater( new UpdateThread( outputArea, &quot; &quot; + getName() + &quot; retrieved values totaling: &quot; + sum + &quot; Terminating &quot; + getName() + &quot; &quot; ) ); } } // end class ConsumeInteger SwingUtilities method invokeLater ensures GUI updates properly
  34. 34. //SharedCell.java // Show multiple threads modifying shared object. import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; // Java extension packages import javax.swing.*; public class SharedCell extends JFrame { // set up GUI public SharedCell() { super ( &quot;Demonstrating Thread Synchronization&quot; ); JTextArea outputArea = new JTextArea( 20 , 30 ); getContentPane().add( new JScrollPane( outputArea ) ); setSize( 500 , 500 ); show(); // set up threads HoldIntegerSynchronized sharedObject = new HoldIntegerSynchronized( outputArea ); ProduceInteger producer = new ProduceInteger( sharedObject, outputArea ); ConsumeInteger consumer = new ConsumeInteger( sharedObject, outputArea ); // start threads producer.start(); consumer.start(); } // execute application public static void main( String args[] ) { SharedCell application = new SharedCell(); application.setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE ); } } // end class SharedCell Set up threads Set up GUI Start threads Execute application
  35. 35. Program Output
  36. 36. 9. Daemon Threads <ul><li>Runs for benefit of other threads </li></ul><ul><ul><li>Do not prevent program from terminating </li></ul></ul><ul><ul><li>Garbage is a daemon thread </li></ul></ul><ul><li>Set daemon thread with method setDaemon </li></ul>10. Runnable Interface <ul><li>Multithreading in a class that extends a class </li></ul><ul><ul><li>A class cannot extend more than one class </li></ul></ul><ul><ul><li>Implements Runnable for multithreading support </li></ul></ul><ul><li>Runnable object grouped with a Thread object </li></ul><ul><li>Program – RandomCharacter.java will be shown it </li></ul>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×