1 // File: SharedCell.java (Fig. 13.4 in JHTP2) 2 // 3 // Show multiple threads modifying shared object. 4 5 public class SharedCell { 6 public static void main( String args[] ) 7 { 8 HoldInteger h = new HoldInteger(); 9 ProduceInteger p = new ProduceInteger( h ); 10 ConsumeInteger c = new ConsumeInteger( h ); 11 12 p.start(); 13 c.start(); 14 } 15 } 16 17 class ProduceInteger extends Thread { 18 private HoldInteger pHold; 19 20 public ProduceInteger( HoldInteger h ) 21 { 22 pHold = h; 23 } 24 25 public void run() 26 { 27 for ( int count = 0; count < 10; count++ ) { 28 // sleep for a random interval 29 try { 30 Thread.sleep( (int) ( Math.random() * 3000 ) ); 31 } 32 catch( InterruptedException e ) { 33 System.err.println( e.toString() ); 34 } 35 36 pHold.setSharedInt( count ); 37 System.out.println( "Producer set sharedInt to " + 38 count ); 39 } 40 41 pHold.setMoreData( false ); 42 } 43 } 44 45 class ConsumeInteger extends Thread { 46 private HoldInteger cHold; 47 48 public ConsumeInteger( HoldInteger h ) 49 { 50 cHold = h; 51 } 52 53 public void run() 54 { 55 int val; 56 57 while ( cHold.hasMoreData() ) { 58 // sleep for a random interval 59 try { 60 Thread.sleep( (int) ( Math.random() * 3000 ) ); 61 } 62 catch( InterruptedException e ) { 63 System.err.println( e.toString() ); 64 } 65 66 val = cHold.getSharedInt(); 67 System.out.println( "Consumer retrieved " + val ); 68 } 69 } 70 } 71 72 class HoldInteger { 73 private int sharedInt = -1; 74 private boolean moreData = true; 75 76 public void setSharedInt( int val ) { sharedInt = val; } 77 78 public int getSharedInt() { return sharedInt; } 79 80 public void setMoreData( boolean b ) { moreData = b; } 81 82 public boolean hasMoreData() { return moreData; } 83 }