单生产者-多消费者/CountDownLatch

参考

生产者消费者模式  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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值