Java Reference
In-Depth Information
'main' tid 0xe4050, status SUSPENDED flags NOSTACKALLOC
blocked@0x13ba20 (0xe4050->|)
Deadlock: all threads blocked on internal events
Abort (core dumped)
Indeed, the read() is never executed because there's no way for produce() to get called and
so the notifyAll() can't happen. To fix this, I want to run the producer and the consumer in
separate threads. There are several ways to accomplish this. I'll just make consume() and
produce() into inner classes Consume and Produce that extend Thread , and their run()
method will do the work of the previous methods. In the process, I'll replace the code that
reads from the console with code that causes both threads to loop for a certain number of
seconds, and change it to be a bit more of a simulation of a distributed producer/consumer
mechanism. The result of all this is the second version, ProdCons2 , shown in
Example 22-13 .
Example 22-13. ProdCons2.java
public
public class
class ProdCons2
ProdCons2 {
/** Throughout the code, this is the object we synchronize on so this
* is also the object we wait() and notifyAll() on.
*/
protected
protected LinkedList < Object > list = new
new LinkedList <>();
protected
protected int
int MAX = 10 ;
protected
protected boolean
boolean done = false
false ; // Also protected by lock on list.
/** Inner class representing the Producer side */
class
class Producer
Producer extends
extends Thread {
public
public void
void run () {
while
while ( true
true ) {
Object justProduced = getRequestFromNetwork ();
// Get request from the network - outside the synch section.
// We're simulating this actually reading from a client, and it
// might have to wait for hours if the client is having coffee.
synchronized
synchronized ( list ) {
while
while ( list . size () == MAX ) { // queue "full"
try
try {
System . out . println ( "Producer WAITING" );
list . wait ();
// Limit the size
} catch
catch ( InterruptedException ex ) {
System . out . println ( "Producer INTERRUPTED" );
}
Search WWH ::




Custom Search