62,616
社区成员
发帖
与我相关
我的任务
分享
public class Plate {
List<Object> eggs = new ArrayList<Object>();
class GetEgg extends Thread {
public GetEgg(String name){
super(name);
}
@Override
public void run() {
synchronized (eggs) {
while (eggs.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggs.clear();
notifyAll();
System.out.println("拿到鸡蛋");
}
}
}
class PutEgg extends Thread {
public PutEgg(String name){
super(name);
}
public void run() {
synchronized (eggs) {
while (eggs.size() > 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggs.add(new Object());
notifyAll();
System.out.println("放入鸡蛋");
}
}
}
public static void main(String[] args) {
Plate plate = new Plate() ;
for(int i =0 ; i< 10 ; i++){
GetEgg g = plate.new GetEgg("getEgg"+i);
PutEgg p = plate.new PutEgg("petEgg"+i);
g.start();
p.start();
}
}
}