Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Introducing Extensions (Chapter 26)......................................................................................................


SOLUTION 26.1....................................................................................................................................


The complete code should look something like:


package com.oozinoz.machine;
import java.util.*;
public class BinStack
{
public static final int STACK_LIMIT = 3;
private Stack stack = new Stack();


synchronized public Bin pop()
{
while (stack.size() == 0)
{
try
{
wait();
Thread.sleep(500);
}
catch (InterruptedException ignore)
{
}
}
if (stack.size() == STACK_LIMIT)
{
notify();
}
return (Bin) stack.pop();
}


synchronized public void push(Bin b)
{
while (stack.size() == STACK_LIMIT)
{
try
{
wait();
Thread.sleep(500);
}
catch (InterruptedException ignore)
{
}
}
if (stack.size() == 0)
{
notify();
}
stack.push(b);
}


public int size()
{
return stack.size();
}
}

Free download pdf