最近在复习操作系统,随手写两种Java实现生产者消费者模型的方式 二、Lock和Condition
一、信号量import java.util.Queue; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Semaphore; class MessageQueue { private static final Semaphore FULL = new Semaphore(0); private static final Semaphore EMPTY = new Semaphore(10); // 初始队列为空 private static final Semaphore MUTEX = new Semaphore(1); // 互斥锁 private static final Random RAND_NUM_PRODUCER = new Random(System.currentTimeMillis()); private static final Queue<Integer> QUEUE = new ConcurrentLinkedQueue<>(); public void produce(){ try { EMPTY.acquire(); MUTEX.acquire(); QUEUE.offer(RAND_NUM_PRODUCER.nextInt(100)); System.out.println("【生产】生产者:" + Thread.currentThread().getName() + " 当前队列:" + QUEUE.size()); } catch (InterruptedException e) { e.printStackTrace(); } FULL.release(); MUTEX.release(); } public void consume(){ try { FULL.acquire(); MUTEX.acquire(); QUEUE.poll(); System.out.println("【消费】消费者:" + Thread.currentThread().getName() + " 当前队列:" + QUEUE.size()); } catch (InterruptedException e) { e.printStackTrace(); } EMPTY.release(); MUTEX.release(); } }
import java.util.Queue; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class MessageQueue { private static final Lock LOCK = new ReentrantLock(); private static final Condition NOT_FULL = LOCK.newCondition(); private static final Condition NOT_EMPTY = LOCK.newCondition(); private static final int MAX_SIZE = 10; private static final Random RAND_NUM_PRODUCER = new Random(System.currentTimeMillis()); private static final Queue<Integer> QUEUE = new ConcurrentLinkedQueue<>(); public void produce() { LOCK.lock(); try{ while(QUEUE.size() == MAX_SIZE){ NOT_FULL.await(); } QUEUE.offer(RAND_NUM_PRODUCER.nextInt(100)); System.out.println("【生产】生产者:" + Thread.currentThread().getName() + " 当前队列:" + QUEUE.size()); NOT_EMPTY.signalAll(); }catch (InterruptedException e){ e.printStackTrace(); }finally { LOCK.unlock(); } } public void consume(){ LOCK.lock(); try{ while(QUEUE.size() == 0){ NOT_EMPTY.await(); } QUEUE.poll(); System.out.println("【消费】消费者:" + Thread.currentThread().getName() + " 当前队列:" + QUEUE.size()); NOT_FULL.signalAll(); }catch (InterruptedException e){ e.printStackTrace(); }finally { LOCK.unlock(); } } } // 以下是测试代码 public class ProducerAndConsumer{ public static void main(String[] args) { MessageQueue messageQueue = new MessageQueue(); Thread producer = new Thread(()->{ while(true) messageQueue.produce(); }); Thread consumer = new Thread(()->{ while(true) messageQueue.consume(); }); producer.start(); consumer.start(); } }
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算