58,454
社区成员
发帖
与我相关
我的任务
分享
import java.util.LinkedList;
public class test22 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Basket basket = new Basket();
Consumer c = new Consumer(basket);
Producer p = new Producer(basket);
c.start();
p.start();
}
}
class Apple {
private int id;
public Apple(int id) {
super();
this.id = id;
}
@Override
public String toString() {
return "Apple" + id;
}
}
class Basket {
boolean flag = false;
int count = 10;
LinkedList<Apple> list = new LinkedList<Apple>();
public synchronized void pushFor() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
push();
flag = false;
notify();
}
public synchronized void popFor() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(count>0) {
pop();
flag = true;
notify();
}
}
public void pop() {
for (int i = 0; i < 5; i++) {
Apple apple = new Apple(i + 1);
list.add(apple);
System.out.println("添加苹果" + apple);
}
}
public void push() {
for (int i = 0; i < 5; i++) {
Apple apple = list.removeFirst();
System.out.println("买走苹果" + apple);
count--;
}
}
}
class Consumer extends Thread {
private Basket basket;
public Consumer(Basket basket) {
super();
this.basket = basket;
}
public void run() {
while (basket.count > 0) {
basket.pushFor();
}
}
}
class Producer extends Thread {
private Basket basket;
public Producer(Basket basket) {
super();
this.basket = basket;
}
public void run() {
while (basket.count > 0) {
basket.popFor();
}
}
}