Java Reference
In-Depth Information
Example 22-12. ProdCons1.java
public
public class
class ProdCons1
ProdCons1 {
protected
protected LinkedList < Object > list = new
new LinkedList <>();
protected
protected void
void produce () {
int
int len = 0 ;
synchronized
synchronized ( list ) {
Object justProduced = new
new Object ();
list . addFirst ( justProduced );
len = list . size ();
list . notifyAll ();
}
System . out . println ( "List size now " + len );
}
protected
protected void
void consume () {
Object obj = null
null ;
int
int len = 0 ;
synchronized
synchronized ( list ) {
while
while ( list . size () == 0 ) {
try
try {
list . wait ();
} catch
catch ( InterruptedException ex ) {
return
return ;
}
}
obj = list . removeLast ();
len = list . size ();
}
System . out . println ( "Consuming object " + obj );
System . out . println ( "List size now " + len );
}
public
public static
static void
void main ( String [] args ) throws
throws IOException {
ProdCons1 pc = new
new ProdCons1 ();
System . out . println ( "Ready (p to produce, c to consume):" );
int
int i ;
while
while (( i = System . in . read ()) != - 1 ) {
char
char ch = ( char
char ) i ;
switch
switch ( ch ) {
case
case 'p' :
pc . produce (); break
break ;
case
case 'c' :
pc . consume (); break
break ;
}
}
Search WWH ::




Custom Search