import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.Random;
public class ProductorCumstomerQueue {
private static final BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
private static Random rand =new Random();
private static List<Thread> threads = new ArrayList<Thread>();
public static void main(String []args) {
for(int i=0; i<2; i++) {
Thread pro = new Thread(new Productor());
threads.add(pro);
}
for(int i=0; i<1; i++) {
Thread cus = new Thread(new Customer());
threads.add(cus);
}
for(int i=0; i<threads.size();i++) {
Thread t = (Thread)threads.get(i);
t.start();
}
}
public static class Productor implements Runnable{
public void run() {
while(true) {
try {
//随机数[0,10)整数
int num = rand.nextInt(10);
queue.put(num);
System.out.println("已生产"+num+"号油条");
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static class Customer implements Runnable{
public void run() {
while(true) {
try {
int num = queue.take();
System.out.println("成功消费"+num+"号油条,当前还剩"+queue.size());
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}