线程基础篇(十五)之使用ReentrantLock实现消费者生产者

/**
 * @author Dora
 * @date 2020/4/8 9:55
 **/
public class QueueLearn {
    // 使用读写锁 实现队列的消费
    // 实现一个队列
  static   ConcurrentLinkedQueue queue=new ConcurrentLinkedQueue();

  // 获取锁
  static ReentrantLock lock=new ReentrantLock();
  static   Condition condition = lock.newCondition();

    public static class Productor implements Runnable{
        // 传入一个要被生产的队列
        @Override
        public void run() {
            lock.lock();
            try {
                // 生产者
                for (int i = 0; i < 10; i++) {
                    if(queue.size()==5){
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.add("这是第"+i+"个我生产的物品");
                    condition.signal();
                }

            }finally {
                lock.unlock();
            }

        }
    }


    public static class Coustomer implements Runnable{
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i = 0; i < 10; i++) {
                    if(queue.size()==0){
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(queue.poll());
                    condition.signal();
                }

            }finally {
                lock.unlock();
            }

        }
    }

    public static void main(String[] args) {
        new Thread(new Productor()).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Coustomer()).start();
    }
}

 

你可能感兴趣的:(多线程)