reentranklock简单实现生产者和消费者模型

package com.qey.interview;

import javax.validation.constraints.Max;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ProductCustomer
 * @Description
 * @Author qianxl
 * @Date 2020-06-29 20:39
 * @Version 1.1
 **/
public class ProductCustomer {
   // private ReentrantLock reentrantLock = new ReentrantLock();
    private Lock lock = new ReentrantLock();
    //创建两个条件变量,一个为缓冲区非满,一个为缓冲区非空
    private final Condition notNull = lock.newCondition();  //lock
    private final Condition notEmpty = lock.newCondition();

    private static Integer count = 0;//设置生产者标记
    private static final Integer MAXCOUNT = 10; //设置生产者最大的值

    class Product implements Runnable {

        @Override
        public void run() {

           for(int i=0;i<MAXCOUNT;i++){
               lock.lock();

                try {

                    while (count == 100) {

                        notNull.await();
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName() + "count's value++" + count);

                    notEmpty.signal();;  //LockSupport.unpark(node.thread); 底层调用unpark 进行解锁


                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }


            }




        }
    }

    class Customer implements Runnable {

        @Override
        public void run() {

            for(int i=0;i<MAXCOUNT;i++) {
                lock.lock();

                try {
                    while (count == 0) {

                        notEmpty.await();

                    }
                    count--;
                    System.out.println(Thread.currentThread().getName() + "count's value--" + count);

                    notNull.signal();
//                   Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }

        }

    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.DiscardOldestPolicy());
        ThreadPoolExecutor threadPoolExecutor2 = new ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.DiscardOldestPolicy());
        Product product = new ProductCustomer().new Product();
        Customer customer = new ProductCustomer().new Customer();

//        new Thread(customer).start();
        new Thread(product).start();
        new Thread(customer).start();
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        new Thread(product).start();
//        new Thread(customer).start();
//        threadPoolExecutor.execute(customer);
//        threadPoolExecutor.execute(product);

//        threadPoolExecutor.execute(product);
//        threadPoolExecutor.execute(customer);

//        for (int i = 0; i < 5; i++) {
//            threadPoolExecutor.execute(customer);
//
//        }
//        for (int i = 0; i < 5; i++) {
//            threadPoolExecutor2.execute(product);
//        }

    }
}

ReentrantLock是一个可重入锁,实现Lock接口,并且支持重新进入的特性。当一个线程通过调用lock方法获取了锁之后,如果再次调用lock方法,该线程不会被阻塞,而是增加了重试次数。 在ReentrantLock内部,它维护了一个Sync内部类,该类实现Lock接口的方法,并且通过调用AQS(AbstractQueuedSynchronizer)的Acquire方法来实现加锁的操作。具体而言,根据ReentrantLock初始化时选择的公平锁或非公平锁,Sync的Lock方法会执行相关的内部类Lock方法,最终会调用AQS的Acquire方法。 因此,ReentrantLock底层的原理是通过Sync内部类的Lock方法调用AQS的Acquire方法来实现加锁操作的。这一过程实现了可重入的特性,使得同一个线程可以多次获取锁而不会被阻塞。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [7-ReentrantLock底层原理分析](https://blog.csdn.net/weixin_45596022/article/details/113817683)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [ReentrankLock的底层原理](https://blog.csdn.net/qq_45974547/article/details/123486390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

利剑 -~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值