Java Reference
In-Depth Information
void
void process ( Object obj ) {
// Thread.sleep(1234) // Simulate time passing
System . out . println ( "Consuming object " + obj );
}
}
ProdCons2 ( int
int nP , int
int nC ) {
for
for ( int
int i = 0 ; i < nP ; i ++)
new
new Producer (). start ();
for
for ( int
int i = 0 ; i < nC ; i ++)
new
new Consumer (). start ();
}
public
public static
static void
void main ( String [] args )
throws
throws IOException , InterruptedException {
// Start producers and consumers
int
int numProducers = 4 ;
int
int numConsumers = 3 ;
ProdCons2 pc = new
new ProdCons2 ( numProducers , numConsumers );
// Let it run for, say, 10 seconds
Thread . sleep ( 10 * 1000 );
// End of simulation - shut down gracefully
synchronized
synchronized ( pc . list ) {
pc . done = true
true ;
pc . list . notifyAll ();
}
}
}
I'm happy to report that all is well with this. It runs for long periods of time, neither crashing
nor deadlocking. After running for some time, I captured this tiny bit of the log:
Produced 1; List size now 118
Consuming object java.lang.Object@2119d0
List size now 117
Consuming object java.lang.Object@2119e0
List size now 116
By varying the number of producers and consumers started in the constructor method, you
can observe different queue sizes that all seem to work correctly.
Search WWH ::




Custom Search