生产者和消费者:

就犹如在快餐店点餐一样,有多个打饭的,有不定时的人来买饭,买饭的人从快餐店自动取餐,如果快餐的库存数量达到下限值时,自动启动打饭的,补充盒饭。

通过while循环的方式,传入变量isStop,来判断是否结束当前while循环。

 package jquery.test.interview;

 import java.util.Vector;

 public class Productor<T> implements Runnable {

     private volatile Vector<T> v;

     private volatile boolean flg = true;
private volatile boolean procFlg = true; public Productor(Vector<T> v){
this.v = v;
} /**
* 生产产品
* @return
*/
public void createProduct(){
synchronized(v){
while(flg){
System.out.println("库存产品数....1.." + v.size());
if((v.isEmpty() || v.size() < 3) && procFlg){
System.out.println("库存紧张,开始生产......");
v.add((T)"product1.....");
v.add((T)"product2.....");
v.add((T)"product3.....");
v.add((T)"product4.....");
v.add((T)"product5.....");
}
//开始等待
try {
System.out.println("库存产品数...2..." + v.size());
v.notifyAll();
v.wait();
} catch (InterruptedException e) {
v.notifyAll();
}
}
if(!flg){
System.out.println("-------------stop proc ---");
v.notifyAll();
}
}
} @Override
public void run() {
createProduct();
} public void stop(){
flg = false;
} public void stopProc(){
procFlg = false;
} }

Productor

 package jquery.test.interview;

 import java.util.Vector;

 public class Customer<T> implements Runnable {

     private volatile Vector<T> vector;

     private volatile boolean flag2 = true;

     public Customer(Vector<T> vector){
this.vector = vector;
} public void getProduct(){
synchronized(vector){
System.out.println("-----stop---customer--222222222-");
while(flag2){
System.out.println("-----flag2----^^^^-");
if(null == vector || vector.isEmpty()){
try {
System.out.println("--没有产品等待中.....");
vector.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("--获取产品使用....." + vector.get(0));
vector.remove(0);
vector.notify();
}
}
if(!flag2){
System.out.println("-----stop---customer---");
vector.notifyAll();
}
}
} @Override
public void run() {
getProduct();
} public void stop(){
flag2 = false;
} }

Customer

     public static void main(String[] args) throws InterruptedException, ExecutionException {
Vector<String> product = new Vector<String>();
ExecutorService pool = Executors.newCachedThreadPool();
Productor proc = new Productor(product);
pool.submit(proc);
Productor proc2 = new Productor(product);
pool.submit(proc2);
List<Customer> cusGroup = new ArrayList<Customer>();
for(int i =0;i<1;i++){
Customer cus = new Customer(product);
cusGroup.add(cus);
pool.submit(cus);
}
Thread.sleep(1000*1);
proc.stopProc(); // 终止生产
proc2.stopProc(); // 终止生产
cusGroup.forEach(cus -> cus.stop()); //关闭客户
proc.stop(); // 关闭生产者,(先关闭消费者,要不然消费者没法关闭)
proc2.stop(); // 关闭生产者,(先关闭消费者,要不然消费者没法关闭)
Thread.sleep(1000*2);
pool.shutdown();
System.out.println("-------------结束");
}

main

05-08 08:10