I'm getting an IllegalMonitorStateException in trying to implement the
above subject. The static declararions made it work, so if this is
part of the problem let me know. I think it has something to do with
the synchronization. I think I'm accessing the bin when I'm not
supposed to be.
**This IS a homework assignment, FYI, and we are using the 1.4.2 API**
So it does have to sleep for a random time, it does have to use as
many consumers as specified as well as number of items. The bin is
either a stack or queue, but that is irrelevant. It does have to
output the exact string and it has to watch for the stop button on the
frame.
Thanks if you can help.
Here's the consumer, which is much like the producer:
// Class Consumer
class Consumer extends Thread
{
// Class data
private int maxItems, currItem, numCons;
private boolean isInterrupted = false;
private static XBin bin;
// Constructor
public Consumer()
{
bin = XThread.bin;
maxItems = ((Number) XThread.sItems.getValue()).intValue();
currItem = 0;
numCons = ((Number) XThread.sConsumer.getValue()).intValue();
isInterrupted = false;
}
// Thread run
public void run()
{
// Catch system interrupts
try {
// Make bin thread-safe
synchronized(bin) {
// Do until requested items produced
while(currItem < maxItems) {
// watch for requested interrupt (stop button)
while (!isInterrupted) {
// Do thread action for as many consumers as
requested
for (int x = 0; x < numCons && !isInterrupted;
x++) {
// Sleep random time
sleep((int)Math.random() * 1000);
// call wait() if nothing to do
while (currItem < maxItems &&
bin.isEmpty()) {
wait();
}
// Notify all when finished
if (currItem >= maxItems &&
bin.isEmpty()) {
notifyAll();
return;
}
// Append Output string
XThread.text.append("item " );
XThread.text.append(new
Integer(currItem).toString());
XThread.text.append(" taken by
Consumer ");
XThread.text.append(new
Integer(x).toString());
XThread.text.append(": ");
bin.printBin();
XThread.text.append("\n");
// Remove Item
bin.pop();
// Release thread and go back to sleep
notifyAll();
currItem++;
} // end for loop
} // number of items produced completed
} // Stop button check
} // End synchronized block
// System interrupt
} catch (InterruptedException it) {
return;
}
} // end run()
// Stop button pressed
public void interrupt() {
isInterrupted = true;
}
}
And for reference, the following:
// Main GUI Code for XThead interface
class XThread extends JFrame {
// Storage bin
static XBin bin;
// threads
private Thread pro;
private Thread con;
// GUI Components
static JToolBar toolBar;
static JPanel mPanel;
static JPanel pcPanel;
static JPanel bPanel;
static JButton button;
static JSpinner sConsumer;
static JSpinner sProducer;
static JSpinner sBin;
static JSpinner sItems;
static JComboBox boxType;
// Output text area
static JTextArea text;
...