- /**
- * 模拟生产者消费者模式-reentrantLock-awit/signAll
- * @author qiuyongAaron
- */
- public class MyContainerTwo {
- LinkedList
- list=
- new
- LinkedList
- ();
- static final int
- MAX=10
- ;
- int
- count=0
- ;
- ReentrantLock lock
- =
- new ReentrantLock();
- Condition producer
- =
- lock.newCondition();
- Condition consumer
- =
- lock.newCondition();
- //生产者线程
- public void
- put(
- int i){
- try {
- lock.lock();
- while
- (list.size()==
- MAX){
- producer.await();
- }
- list.add(i);
- ++
- count;
- consumer.signalAll();//通知消费者来消费
- }
- catch (InterruptedException e){
- e.printStackTrace();
- }finally{
- lock.unlock();
- }
- }
- //消费者线程
- public int get(){
- try{
- lock.lock();
- while
- (list.size()==0
- ){
- consumer.await();
- }
- int
- num=
- list.removeFirst();
- count
- --
- ;
- producer.signalAll();//通知生产者生产
- return num;
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- lock.unlock();
- }
- return
- 0
- ;
- }
- public static void main(String[] args) {
- MyContainerTwo container
- =
- new MyContainerTwo();
- //制造10个消费者
- for
- (
- int
- i=0;i<10;i++
- ){
- new
- Thread(()->
- {
- for
- (
- int
- j=0;j<5;j++
- ) System.out.println(container.get());
- },
- "c"+
- i).start();
- }
- try {
- TimeUnit.SECONDS.sleep(
- 2
- );
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //制造2个生产者
- for
- (
- int
- i=0;i<2;i++
- ){
- new
- Thread(()->
- {
- for
- (
- int
- j=0;j<25;j++
- ) container.put(j);
- },
- "p"+
- i).start();
- }
- }
- }
来源: http://www.cnblogs.com/qiuyong/p/7102779.html