import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
Baskets baskets = new Baskets();
Producters producters = new Producters(baskets);
Consumers consumers = new Consumers(baskets);
producters.start();//生産者進行生産
consumers.start();//消費者進行消費
}
}
/**
* 消費者線程
* @author Administrator
*
*/
class Consumers extends Thread{
private Baskets baskets = null;
public Consumers(Baskets baskets) {
this.baskets = baskets;
}
@Override
public void run() {
baskets.popApple();
}
}
/**
* 生産者線程
* @author Administrator
*
*/
class Producters extends Thread{
private Baskets baskets = null;
public Producters(Baskets baskets) {
this.baskets = baskets;
}
@Override
public void run() {
baskets.pushApple();
}
}
class Baskets{
private LinkedList<Apples> basket = new LinkedList<>();//建立一個籃子原來存放Apples
/**
* 分四次取出蘋果
*/
public synchronized void popApple() {//需要聲明同步方法才能獲得該對象的鎖
for(int i=0;i<20;i++) {
pop();
}
}
/**
* 分四次放蘋果
*/
public synchronized void pushApple() {//需要聲明同步方法才能獲得該對象的鎖
for(int i=0;i<20;i++) {
Apples apples = new Apples(i);
push(apples);
}
}
/**
* 取出蘋果
* @param apples
*/
public void pop() {
if(basket.size() == 0) {//當籃子裡面的蘋果為0,通知并等待生産者來生産
try {
wait();//等待并釋放目前該對象鎖
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("取出"+basket.removeFirst().toString());
notify();//通知生産者來生産
}
/**
* 存放蘋果
* @param apples
*/
public void push(Apples apples) {
if(basket.size() == 5) {//當籃子裡面的蘋果滿了通知并等待消費者來消費
try {
wait();//等待并釋放目前該對象鎖
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
basket.addFirst(apples);
System.out.println("存放"+apples.toString());
notify();//通知消費者來消費
}
}
class Apples{
private int id;
public Apples(int id) {//給每個蘋果标号
this.id = id ;
}
public String toString() {
return "蘋果"+(id+1);
}
}