参考
生产者消费者模式 http://www.cnblogs.com/phinecos/archive/2011/08/23/2151191.html
countDownLatch:http://www.itzhai.com/the-introduction-and-use-of-a-countdownlatch.html
public class producer implements Runnable{
static AtomicInteger y=new AtomicInteger(0);
BlockingQueue workQueue;
String threadname;
CountDownLatch begin;
CountDownLatch end;
producer(BlockingQueue workQueue,String threadname,CountDownLatch begin,CountDownLatch end){
this.workQueue=workQueue;
this.threadname= threadname;
this.begin= begin;
this.end=end;
}
@Override
public void run() {
try {
begin.await();
TestProducer tp=new TestProducer();
String uuid = UUID.randomUUID().toString();
tp.setId(uuid);
tp.setPname("name"+Math.round(Math.random()*1000));
tp.setDescn("descn"+producer.y.incrementAndGet());
tp.setState(threadname);
System.out.println("threadname="+threadname+"\tid="+tp.getDescn());
workQueue.put(tp);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
end.countDown();
}
}
}
public class consumer implements Runnable{
static AtomicInteger i=new AtomicInteger(0);
BlockingQueue workQueue;
String threadname;
consumer(BlockingQueue workQueue,String threadname){
this.workQueue=workQueue;
this.threadname=threadname;
}
@Override
public void run() {
try {
while(true){
TestProducer tp=(TestProducer)workQueue.take();
System.out.println(consumer.i.incrementAndGet()+"\tproThreadName="+tp.getState()+"" +
"\tconThreadName="+threadname+"\tdescn="+tp.getDescn());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
BlockingQueue productQueue=new LinkedBlockingQueue();
BlockingQueue workQueue=new LinkedBlockingQueue<Runnable>();
ThreadPoolExecutor productPool=new ThreadPoolExecutor(3,10,1, TimeUnit.SECONDS,workQueue);
//ExecutorService es=Executors.newCachedThreadPool();
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(50);
for(int i=0;i<50;i++){
producer p=new producer(productQueue,"thread-"+i,begin,end);
productPool.execute(p);
}
begin.countDown();
end.await();
System.out.println("生产结束!");
Thread.sleep(500);
BlockingQueue consumerQueue=new LinkedBlockingQueue<Runnable>();
ThreadPoolExecutor consumerPool=new ThreadPoolExecutor(3,6,1, TimeUnit.SECONDS,consumerQueue);
for(int i=0;i<15;i++){
consumer c=new consumer(productQueue,"t-"+i);
consumerPool.execute(c);
}
productPool.shutdown();
consumerPool.shutdown();
}
}