package studybymyself;
import java.util.LinkedList;
/**
* 描述:生产者生产5个苹果,停止生产,并告诉消费者。
* 让消费者消费完5个苹果后,停止消费,并告诉生产者。
* 生产者继续生产5个苹果~~~~~循环4轮
*
* 苹果、篮子、生产者、消费者对象 那么需要写4个类
* @author ASUS
* @date 2018年7月30日
*/
public class ProductorConsumerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Basket basket = new Basket();
Productor productor = new Productor(basket);
Consumer consumer = new Consumer(basket);
productor.start();
consumer.start();
}
}
class Productor extends Thread{
private Basket basket = null;
/**
* @param basket
*/
public Productor(Basket basket) {
super();
this.basket = basket;
}
@Override
public void run() {
basket.pushTimes();
}
}
class Consumer extends Thread{
private Basket basket = null;
/**
* @param basket
*/
public Consumer(Basket basket) {
super();
this.basket = basket;
}
@Override
public void run() {
basket.popTimes();
}
}
class Apples{
private int id;
/**
* @param id
*/
public Apples(int id) {
this.id = id;
}
@Override
public String toString() {
return "Apples [id=" + id + "]";
}
}
class Basket{
private LinkedList<Apples> basket = new LinkedList<Apples>();
public synchronized void pushTimes(){
for(int i = 0;i < 20;i++) {
Apples apple = new Apples(i);
push(apple);
}
}
public synchronized void popTimes(){
for(int i = 0;i < 20;i++) {
pop();
}
}
//生产者放苹果
public void push(Apples apple) {
//当篮子当中有5个苹果时,进入等待
if(basket.size() ==5) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
basket.add(apple);
System.out.println("存放:"+apple.toString());
notify();//通知消费者来消费
}
//消费者吃苹果
public void pop() {
//当篮子当中没苹果时,进入等待
if(basket.size() ==0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Apples apple = basket.removeLast();
System.out.println("吃掉:"+apple.toString());
notify();//通知生产者来生产
}
}