使用锁模拟写一个固定容量同步容器(马士兵并发笔记)

写一个固定容量同步容器,拥有put和get方法,以及getCount方法,能够支持多个生产者和多个消费者线程拥塞调用。

1.使用synchronized锁或ReentrantLock锁实现

1)使用synchronized锁的notify、notifyAll来实现

基本思路:使用put方法向容器中添加元素,使用get方法从容器中取出元素,在使用put方法添加元素的时候进行判断,如果容器已经满了,此时调用wait()方法,使用添加线程阻塞,等待消费线程取出元素,腾出容器空间后才能再向其中添加元素,同理当使用get方法获取元素的时候,如果同期已经为空,此时要调用wait()方法,使得取出线程阻塞,等待添加线程添加元素,容器有值后才能再从容器中取出元素。

  1. public class MyContainer1<T> {
  2. final private LinkedList<T> lists = new LinkedList<>();
  3. final private int MAX = 10; //最多10个元素
  4. private int count = 0;
  5. public synchronized void put(T t) {
  6. while(lists.size() == MAX) { //想想为什么用while而不是用if?
  7. try {
  8. this.wait(); //effective java
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. lists.add(t);
  14. ++count;
  15. System.out.println("生产者容器中的物品数: "+count);
  16. this.notifyAll(); //通知消费者线程进行消费
  17. }
  18. public synchronized T get() {
  19. T t = null;
  20. while(lists.size() == 0) {
  21. try {
  22. this.wait();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. t = lists.removeFirst();
  28. count --;
  29. System.out.println("消费者容器中的物品数: "+count);
  30. this.notifyAll(); //通知生产者进行生产
  31. return t;
  32. }
  33. public static void main(String[] args) {
  34. MyContainer1<String> c = new MyContainer1<>();
  35. //启动消费者线程
  36. for(int i=0; i<10; i++) {
  37. new Thread(()->{
  38. for(int j=0; j<5; j++) //生产者执行了50次
  39. c.get();
  40. //System.out.println(c.get());
  41. }, "c" + i).start();
  42. }
  43. try {
  44. TimeUnit.SECONDS.sleep(2);
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. }
  48. //启动生产者线程
  49. for(int i=0; i<2; i++) {
  50. new Thread(()->{
  51. for(int j=0; j<25; j++) //消费者执行了50次
  52. c.put(Thread.currentThread().getName() + " " + j);
  53. }, "p" + i).start();
  54. }
  55. }
  56. }
public static void main(String[] args) {MyContainer1<String> c = new MyContainer1<>();//启动消费者线程for(int i=0; i<10; i++) {new Thread(()->{for(int j=0; j<5; j++) //生产者执行了50次c.get();//System.out.println(c.get());}, "c" + i).start();}try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}//启动生产者线程for(int i=0; i<2; i++) {new Thread(()->{for(int j=0; j<25; j++) //消费者执行了50次c.put(Thread.currentThread().getName() + " " + j);}, "p" + i).start();}}}

说明:如下的代码中应当注意三点:

        第一点:在count--后,this.notifyAll()的作用是处理这样一种情况:如果容器满了,此时生产者线程被阻塞,这是消费者线程消费了元素后,注意要唤醒生产者线程,如果没有这一步,那么只有消费者线程执行,消费者线程都执行完或者执行到容量为空时,此时会出现生成者线程一直被阻塞等待锁的情况,此时程序将停留在这里。

        第二点:注意这里的while(lists.size()==0)不能换成if(lists.size())==0,分析:考虑这样一种情况,容器为空,消费线程t1和t2调用wait()方法进入阻塞,此时生产线程t3生产了一个元素后,唤醒所有的线程后,此时线程t1从this.wait()后面直接执行,消费一个元素后,线程t2从this.wait()后的代码直接执行,并不会判断,此时容器已经为空,但它依旧取出一个元素,导致了报错。

        第三点:this.notifyAll()不能换成this.notify(),因为如果换成this.notify()函数,此时只唤醒一个线程,假设这样一种状态,消费者线程消费了最后一个元素后,容器为空,此时消费者线程本打算唤醒生产者线程,结果却唤醒了消费者线程,消费者线程在执行了while(lists.size()==0)中的this.wait()方法后进入阻塞状态,此时被唤醒的消费者线程也进入阻塞状态,程序死锁。

2)使用ReentrantLock锁的notify、notifyAll来实现

  1. public class MyContainer2<T> {
  2. final private LinkedList<T> lists = new LinkedList<>();
  3. final private int MAX = 10; //最多10个元素
  4. private int count = 0;
  5. private Lock lock = new ReentrantLock();
  6. private Condition producer = lock.newCondition();
  7. private Condition consumer = lock.newCondition();
  8. public void put(T t) {
  9. try {
  10. lock.lock();
  11. while(lists.size() == MAX) { //想想为什么用while而不是用if?
  12. producer.await(); //当消费者线程们执行到这里的时候等待
  13. }
  14. lists.add(t);
  15. ++count;
  16. System.out.println("里面有个数:"+count);
  17. consumer.signalAll(); //通知消费者线程进行消费
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. } finally {
  21. lock.unlock();
  22. }
  23. }
  24. public T get() {
  25. T t = null;
  26. try {
  27. lock.lock();
  28. while(lists.size() == 0) {
  29. consumer.await(); //当生产者线程执行到这里的等待
  30. }
  31. t = lists.removeFirst();
  32. count --;
  33. System.out.println("里面有个数:"+count);
  34. producer.signalAll(); //通知生产者的线程们进行生产
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. } finally {
  38. lock.unlock();
  39. }
  40. return t;
  41. }
  42. public static void main(String[] args) {
  43. MyContainer2<String> c = new MyContainer2<>();
  44. //启动消费者线程
  45. for(int i=0; i<10; i++) {
  46. new Thread(()->{
  47. for(int j=0; j<5; j++)
  48. c.get();
  49. //System.out.println(c.get());
  50. }, "c" + i).start();
  51. }
  52. try {
  53. TimeUnit.SECONDS.sleep(2);
  54. } catch (InterruptedException e) {
  55. e.printStackTrace();
  56. }
  57. //启动生产者线程
  58. for(int i=0; i<2; i++) {
  59. new Thread(()->{
  60. for(int j=0; j<25; j++)
  61. c.put(Thread.currentThread().getName() + " " + j);
  62. }, "p" + i).start();
  63. }
  64. }
  65. }

说明:ReentrantLock锁的好处,可以创建多个Condition队列,如上面的代码,创建了consumer和producer队列,在get方法中会将执行该方法的消费者线程通过consumer.await()方法阻塞consumer队列中,同时在get方法中可以只唤醒consumer(生产者)队列的线程。

2.直接使用BlockingQueue实现

1)BlockingQueue是一个接口,并非具体实现,常见的BlockingQueue实现有ArrayBlockingQueue和LinkedBlockingQueue。ArrayBlockingQueue是基于数组实现,而LinkedBlockingQueue是基于链表实现

2)向队列中压入元素课可以使用offer()方法和put()方法,对于offer()方法,如果队列已经满了,它就会立即返回false,如果没有满,则执行正常的入队列操作,而put()方法,如果队列满了,它会一直等待,直到队列中有空闲的位置

3)从队列中弹出元素,可以使用poll()方法和take()方法,如果队列为空poll()方法直接返回null,而take()方法会一直等待,直到队列内有可用元素。

4)put()方法和take()方法体现Blocking的关键

使用LinkedBlockingQueue实现上面的固定同步容器代码如下:

  1. public class TestBlockingQueue<T> {
  2. //final private LinkedList<T> lists = new LinkedList<>();
  3. BlockingQueue<T> queue = new LinkedBlockingDeque<>(10);
  4. //生产者线程
  5. public void put(T t) {
  6. try {
  7. queue.put(t);
  8. System.out.println("里面有个数:"+queue.size());
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. public T get() {
  14. T t = null;
  15. try {
  16. queue.take();
  17. System.out.println("里面有个数:"+queue.size());
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. return t;
  22. }
  23. public static void main(String[] args) {
  24. TestBlockingQueue<String> c = new TestBlockingQueue<>();
  25. //启动消费者线程
  26. for(int i=0; i<10; i++) {
  27. new Thread(()->{
  28. for(int j=0; j<5; j++)
  29. c.get();
  30. //System.out.println(c.get());
  31. }, "c" + i).start();
  32. }
  33. try {
  34. TimeUnit.SECONDS.sleep(2);
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. }
  38. //启动生产者线程
  39. for(int i=0; i<2; i++) {
  40. new Thread(()->{
  41. for(int j=0; j<25; j++)
  42. c.put(Thread.currentThread().getName() + " " + j);
  43. }, "p" + i).start();
  44. }
  45. }
  46. }

原文地址:https://www.cnblogs.com/jpfss/p/9229546.html