引用网上的例子,在明知到生产者 一个生产者,几个抢食者,如果通知所有的抢食者执行的操作会发生异常的时候,使用notify
import java.util.ArrayList;
import java.util.List;
class Widget{}
class WidgetMaker extends Thread{
List finishedWidgets = new ArrayList();
public void run(){
try{
while(true){
Thread.sleep(5000);
Widget w = new Widget();
Widget i = new Widget();
Widget d = new Widget();
synchronized (finishedWidgets) {
finishedWidgets.add(w);
finishedWidgets.add(i);
finishedWidgets.add(d);
finishedWidgets.notifyAll();
}
}
}catch(InterruptedException e)
{}
}
public Widget waitForWiget() {
synchronized (finishedWidgets) {
if (finishedWidgets.size() == 0) {
try {
finishedWidgets.wait();
} catch (InterruptedException e) {
}
}
return (Widget) finishedWidgets.remove(0);
}
}
}
public class WidgetUser extends Thread{
private WidgetMaker maker;
public WidgetUser(String name,WidgetMaker maker){
super(name);
this.maker = maker;
}
public void run(){
Widget w = maker.waitForWiget();
System.out.println(getName()+"got a widget");
}
public static void main(String[] args){
WidgetMaker maker = new WidgetMaker();
maker.start();
new WidgetUser("Lenny", maker).start();
new WidgetUser("Moe", maker).start();
new WidgetUser("Curly", maker).start();
}
}