public class SynchronizedBuffer implements Buffer
1: //SynchronizedBuffer.java
2: //SynchronizedBuffer synchronizes access to a single shared integer.
3:
4: public class SynchronizedBuffer implements Buffer
5: {
6: private int buffer = -1; // shared by producer and consumer threads
7: private int occupiedBufferCount = 0; // count of occupied buffers
8:
9: // place value into buffer
10: public synchronized void set( int value )
11: {
12: // for output purposes, get name of thread that called this method
13: String name = Thread.currentThread().getName();
14:
15: // while there are no empty locations, place thread in waiting state
16: while ( occupiedBufferCount == 1 )
17: {
18: // output thread information and buffer information, then wait
19: try
20: {
21: System.err.println( name + " tries to write." );
22: displayState( "Buffer full. " + name + " waits." );
23: wait();
24: }
25:
26: // if waiting thread interrupted, print stack trace
27: catch ( InterruptedException exception )
28: {
29: exception.printStackTrace();
30: }
31:
32: } // end while
33:
34: buffer = value; // set new buffer value
35:
36: // indicate producer cannot store another value
37: // until consumer retrieves current buffer value
38: ++occupiedBufferCount;
39:
40: displayState( name + " writes " + buffer );
41:
42: notify(); // tell waiting thread to enter ready state
43:
44: } // end method set; releases lock on SynchronizedBuffer
45:
46: // return value from buffer
47: public synchronized int get()
48: {
49: // for output purposes, get name of thread that called this method
50: String name = Thread.currentThread().getName();
51:
52: // while no data to read, place thread in waiting state
53: while ( occupiedBufferCount == 0 )
54: {
55:
56: // output thread information and buffer information, then wait
57: try
58: {
59: System.err.println( name + " tries to read." );
60: displayState( "Buffer empty. " + name + " waits." );
61: wait();
62: }
63:
64: // if waiting thread interrupted, print stack trace
65: catch ( InterruptedException exception )
66: {
67: exception.printStackTrace();
68: }
69:
70: } // end while
71:
72: // indicate that producer can store another value
73: // because consumer just retrieved buffer value
74: --occupiedBufferCount;
75:
76: displayState( name + " reads " + buffer );
77:
78: notify(); // tell waiting thread to become ready to execute
79:
80: return buffer;
81:
82: } // end method get; releases lock on SynchronizedBuffer
83:
84: // display current operation and buffer state
85: public void displayState( String operation )
86: {
87: StringBuffer outputLine = new StringBuffer( operation );
88: String blanks = new String("");
89: for (int j=1; j<=40-operation.length(); j++) blanks += " ";
90: outputLine.append(blanks);
91: //outputLine.setLength( 40 );
92: outputLine.append( buffer + "\t\t" + occupiedBufferCount );
93: System.err.println( outputLine );
94: System.err.println();
95: }
96:
97: } // end class SynchronizedBuffer
98: