package cn.ljs.FristSync;
import java.util.ArrayList;
public class ProductorDemo {
public static void main(String[] args) {
Pool pool = new Pool();
Productor01 productor01 = new Productor01("productor1", pool);
Productor01 productor02 = new Productor01("productor2", pool);
Comsumer01 comsumer01 = new Comsumer01("comsumer1", pool);
Comsumer01 comsumer02 = new Comsumer01("comsume2", pool);
productor01.start();
productor02.start();
comsumer01.start();
comsumer02.start();
}
}
class Productor01 extends Thread{
private String name;
private Pool pool;
private static int i=1;
public Productor01(String name, Pool pool){
this.name = name;
this.pool = pool;
}
public void run(){
while (true) {
pool.add(i);
System.out.println(name + " add: " + i);
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Comsumer01 extends Thread{
private String name;
private Pool pool;
public Comsumer01(String name, Pool pool){
this.name = name;
this.pool = pool;
}
public void run(){
while (true) {
int n = pool.remove();
System.out.println(name + " remove: " + n);
}
}
}
class Pool{
ArrayList<Integer> list = new ArrayList<Integer>();
private int Max =100;
public void add(int n){
synchronized (this) {
try {
while( list.size() >= Max) {
this.wait();
}
list.add(n);
this.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int remove() {
synchronized (this) {
try {
while( list.size() == 0 ){
this.wait();
}
int n = list.remove(0);
this.notify();
return n;
} catch (Exception e) {
e.printStackTrace();
}
}
return -1;
}
}