class Counter{
Vector coffees;
Countre(){
coffees = new Vector();
}
ここからスレッドを同期させるメソッドを指定する。
public synchronized void getCoffee(String name)
throws InterruptedException{
//だれか一人を起こす瞬間に、他のだれかがコーヒーを
//持って行ってしまう可能性があるのでwhile
while(coffee.size() == 0){
System.out.println(name +"can NOT drink a COFFEE!");
wait();
}
coffee.removeElementAt(0);
System.out.println(name +"can drink & COFFEE!");
System.out.println(coffees.toString());
if(coffee.size() == 4) notifyAll();
}
で、ここからもスレッドの同期をさせる
public synchronized void putCoffee()
throws InterruptedException{
coffees.addElement(new String("coffee"));
if(coffee.size()>4){
System.out.println("It's AKAJI!");
wait();
}
System.out.println("Master made & COFFEE");
System.out.println(coffee.toString());
if(coffee.size() == 1)notify();
}
}