// SharedCell1.java // Multiple Threads modify a shared object // No synchronization // This is an example of Deitel & Deitel, but turned // into an applet. import java.applet.Applet; import java.awt.*; public class SharedCell1 extends Applet{ TextField producertext, consumertext; ProduceInteger1 p; ConsumeInteger1 c; HoldInteger1 h; public void init() { // Set up the awt components. producertext = new TextField(40); consumertext = new TextField(40); add( producertext); add( consumertext); // Set up the shared object. h = new HoldInteger1(); } // Start the two threads. public void start(){ p = new ProduceInteger1(h, this); c = new ConsumeInteger1(h, this); p.start(); c.start(); } public void stop(){ p.stop(); c.stop(); } // Methods to change the text fields. public void setProducerText(String s){ producertext.setText(s); repaint(); } public void setConsumerText(String s){ consumertext.setText(s); repaint(); } } class ProduceInteger1 extends Thread { private HoldInteger1 pHold; private SharedCell1 theapplet; // Constructor needs to know shared object and applet. public ProduceInteger1( HoldInteger1 h,SharedCell1 s) { pHold = h; theapplet = s; } public void run() { // Count to 10 in shared object. // Sleep random amounts of time to let consumer in. for( int count = 0; count < 10; count++) { pHold.setSharedInt(count); theapplet.setProducerText("Producer set sharedInt to " + count); try { sleep( (int) (Math.random() * 3000)); } catch( InterruptedException e) { } } } } class ConsumeInteger1 extends Thread { private HoldInteger1 cHold; private SharedCell1 theapplet; // This thread needs to know the shared object and the applet. public ConsumeInteger1( HoldInteger1 h, SharedCell1 s) { theapplet = s; cHold = h; } // Go out 10 times and retrieve whatever is in the // shared object. Sleep random amounts of time to // let consumer in. public void run() { int val; val = cHold.getSharedInt(); theapplet.setConsumerText("Consumer gets " + val); while( val != 9 ) { try { sleep( (int) (Math.random() * 3000)); } catch( InterruptedException e) { } val = cHold.getSharedInt(); theapplet.setConsumerText("Consumer retrieves " + val); } } } class HoldInteger1 { // Container for one integer, with methods // for setting and retrieving it. private int sharedInt; public void setSharedInt( int val ) { sharedInt = val; } public int getSharedInt() { return sharedInt; } }