26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

868 Multithreading Chapter 15<br />

a DecimalFormat object <strong>to</strong> format the contents of the array buffer. The format control<br />

string " #;-#" indicates a positive number format and a negative number format—<br />

the formats are separated by a semicolon (;). The format specifies that positive values<br />

should be preceded by a space and negative values should be preceded by a minus sign.<br />

1 // Fig. 15.16: SharedCell.java<br />

2 // Show multiple threads modifying shared object.<br />

3<br />

4 // <strong>Java</strong> core packages<br />

5 import java.awt.*;<br />

6 import java.awt.event.*;<br />

7 import java.text.DecimalFormat;<br />

8<br />

9 // <strong>Java</strong> extension packages<br />

10 import javax.swing.*;<br />

11<br />

12 public class SharedCell extends JFrame {<br />

13<br />

14 // set up GUI<br />

15 public SharedCell()<br />

16 {<br />

17 super( "Demonstrating Thread Synchronization" );<br />

18<br />

19 JTextArea outputArea = new JTextArea( 20, 30 );<br />

20 getContentPane().add( new JScrollPane( outputArea ) );<br />

21<br />

22 setSize( 500, 500 );<br />

23 show();<br />

24<br />

25 // set up threads<br />

26 HoldIntegerSynchronized sharedObject =<br />

27 new HoldIntegerSynchronized( outputArea );<br />

28<br />

29 ProduceInteger producer =<br />

30 new ProduceInteger( sharedObject, outputArea );<br />

31<br />

32 ConsumeInteger consumer =<br />

33 new ConsumeInteger( sharedObject, outputArea );<br />

34<br />

35 // start threads<br />

36 producer.start();<br />

37 consumer.start();<br />

38 }<br />

39<br />

40 // execute application<br />

41 public static void main( String args[] )<br />

42 {<br />

43 SharedCell application = new SharedCell();<br />

44<br />

45 application.setDefaultCloseOperation(<br />

46 JFrame.EXIT_ON_CLOSE );<br />

47 }<br />

Fig. Fig. 15.16 15.16 Threads modifying a shared array of cells (part 1 of 2).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!