多线程面试题(二)---手写生产者消费者模式

1.手写实现生产者,消费者

生产者A将num更新成1,消费者将num更新成0,轮训执行10次。

public class LockDemo {

  public static void main (String[] args) {

    //实现生产者,消费者
    // 判断等待,业务,通知
    Data data = new Data();
    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        try {
          data.increment();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }, "A").start();

    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        try {
          data.decrement();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }, "B").start();
  }

}

class Data {

  private int num = 0;

  Lock lock = new ReentrantLock();
  Condition condition = lock.newCondition();

  public void increment () {
    lock.lock();
    try {

      while (num != 0) {
        condition.await();
      }
      num = num + 1;
      System.out.println(Thread.currentThread().getName() + "->  num:" + num);
      condition.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void decrement () {
    lock.lock();
    try {
      while (num != 1) {
        condition.await();
      }
      num = num - 1;

      System.out.println(Thread.currentThread().getName() + "->  num:" + num);
      condition.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }
}

顺序执行

package com.fp.coupon.rest.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo2 {

  public static void main (String[] args) {

    //实现生产者,消费者
    // 判断等待,业务,通知
    Data2 data = new Data2();
    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        data.A();
      }
    }, "A").start();

    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        try {
          data.B();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }, "B").start();

    new Thread(() -> {
      for (int i = 0; i < 10; i++) {
        try {
          data.C();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }, "C").start();

  }



}

class Data2 {

  private int num = 1;

  Lock lock = new ReentrantLock();
  Condition condition1 = lock.newCondition();
  Condition condition2 = lock.newCondition();
  Condition condition3 = lock.newCondition();

  public void A () {
    lock.lock();
    try {

      while (num != 1) {
        condition1.await();
      }
      num = 2;
      System.out.println(Thread.currentThread().getName() + "=>  AAAAAA");
      condition2.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void B () {
    lock.lock();
    try {
      while (num != 2) {
        condition2.await();
      }
      num = 3;
      System.out.println(Thread.currentThread().getName() + "=>  BBBBBB");
      condition3.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void C () {
    lock.lock();
    try {

      while (num != 3) {
        condition3.await();
      }
      num = 1;
      System.out.println(Thread.currentThread().getName() + "=>  CCCCCC");
      condition1.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

}


狂神JUC笔记:https://www.kuangstudy.com/bbs/1374937897278402561

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者-消费者模式是一种经典的多线程模式,其中一个或多个生产者生成数据并将其放入缓冲区,而一个或多个消费者从缓冲区中读取数据并进行处理。下面是一个使用Python实现的生产者-消费者模式的简单例子: ```python import threading import queue import time # 定义一个缓冲区 buffer = queue.Queue(maxsize=10) # 生产者线程函数 def producer(): while True: # 生产一个数据 data = time.time() # 将数据放入缓冲区 buffer.put(data) print("Producer: produced item %s" % data) # 等待一段时间 time.sleep(1) # 消费者线程函数 def consumer(): while True: # 从缓冲区中取出一个数据 data = buffer.get() print("Consumer: consumed item %s" % data) # 处理数据 # ... # 通知缓冲区数据已经被处理 buffer.task_done() # 创建生产者和消费者线程 producer_thread = threading.Thread(target=producer) consumer_thread = threading.Thread(target=consumer) # 启动线程 producer_thread.start() consumer_thread.start() # 等待所有线程结束 producer_thread.join() consumer_thread.join() ``` 在这个例子中,我们使用了Python内置的`queue`模块来实现缓冲区。首先,我们创建了一个`Queue`对象作为缓冲区,并设置了最大容量为10。然后,我们定义了生产者和消费者线程函数,分别用于生成数据和处理数据。在生产者线程中,我们使用`put`方法将数据放入缓冲区。在消费者线程中,我们使用`get`方法从缓冲区中取出数据,并使用`task_done`方法通知缓冲区数据已经被处理。 最后,我们创建生产者和消费者线程,并启动它们。在主线程中,我们使用`join`方法等待所有线程结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值