其中读者写者和贪睡的理发师使用的Semaphore类;生产者消费者使用的是管程。

读者写者

class Semaphore
{int value;public Semaphore(int v){this.value = v;}public synchronized void p(){value -= 1;if (value < 0){try{wait();} catch (InterruptedException e){e.printStackTrace();}}}public synchronized void v(){value += 1;if (value <= 0){this.notify();}}
}class Reader implements Runnable
{int count;Semaphore rmutex;Semaphore wmutex;public Reader(int c, Semaphore r, Semaphore w){this.count = c;this.rmutex = r;this.wmutex = w;}public void run(){while (true){rmutex.p();if (count == 0){wmutex.p();System.out.println("****************************reader has got lock no writer is allowed*************************");System.out.println("ReaderReaderReaderReader Thread: " + Thread.currentThread().getName()+ " current count= " + count);}count++;rmutex.v();System.out.println("I AM Reader: " + Thread.currentThread().getName() + " count= " + count + " I am DOING SOME JOB!");try{Thread.sleep((long) (Math.random() * 1000));} catch (InterruptedException e){e.printStackTrace();}rmutex.p();count--;System.out.println("I AM Reader: " + Thread.currentThread().getName() + " count= " + count + " I am quiting work");if (count == 0){
//                System.out.println(
//                        "ReaderReaderReaderReader Thread: " + Thread.currentThread().getName() + "give up lock");wmutex.v();System.out.println("****************************readers all give up lock*************************");System.out.println();}rmutex.v();try{Thread.sleep((long) (Math.random() * 1000));} catch (InterruptedException e){e.printStackTrace();}}}
}class Writer implements Runnable
{Semaphore wmutex;public Writer(Semaphore w){this.wmutex = w;}public void run(){while (true){wmutex.p();System.out.println("====================writer has got lock no reader is allowed===================================");System.out.println("WriterWriterWriter Thread: " + Thread.currentThread().getName());System.out.println("begin writting data...");try{Thread.sleep((long) (Math.random() * 1000));} catch (InterruptedException e){e.printStackTrace();}System.out.println("finish writting data.");wmutex.v();System.out.println("=======================================writer give up lock==========================================");System.out.println();}}
}public class ReaderWriter
{public static void main(String[] args){int count = 0;Semaphore rmutex = new Semaphore(1);Semaphore wmutex = new Semaphore(1);Reader reader = new Reader(count, rmutex, wmutex);Writer writer = new Writer(wmutex);Thread r1 = new Thread(reader);Thread r2 = new Thread(reader);Thread w1 = new Thread(writer);Thread w2 = new Thread(writer);w1.start();r1.start();w2.start();try{Thread.sleep(1000);} catch (InterruptedException e){e.printStackTrace();}r2.start();}
}

贪睡的理发师

class Semaphore{int value;public Semaphore(int v) {this.value = v;}public synchronized void p() {value--;if(value < 0) {try {wait();}catch(InterruptedException e) {e.printStackTrace();}}}public synchronized void v() {value++;if(value <= 0) {notifyAll();}}
}class Customer implements Runnable{Semaphore mutex;Semaphore customer;Semaphore barber;int index;public Customer(int index, Semaphore mutex, Semaphore customer, Semaphore barber) {this.index = index;this.mutex = mutex;this.customer = customer;this.barber = barber;}public void run() {mutex.p();if(BC.count >= BC.MAX) {System.out.println("椅子已经坐满,顾客" + index + " 离开");mutex.v();}else {BC.count++;customer.v(); // 通知理发师等待理发人数加1mutex.v();barber.p();       // 抢夺理发师System.out.println("顾客" + index + " 开始理发");
//          System.out.println("顾客: " + Thread.currentThread().getName().toString() + " 正在理发");}}
}class Barbe implements Runnable{Semaphore mutex;Semaphore customer;Semaphore barber;public Barbe(Semaphore mutex, Semaphore customer, Semaphore barber) {this.mutex = mutex;this.customer = customer;this.barber = barber;}public void run() {while(true) {customer.p();mutex.p();BC.count--;barber.v();mutex.v();System.out.println(" 理发师理发");try {Thread.sleep((long)(Math.random() * 1000));}catch(InterruptedException e) {e.printStackTrace();}}}
}public class BC{static int count;static int MAX = 5;static Semaphore mutex = new Semaphore(1); static Semaphore barber = new Semaphore(1);static Semaphore customer = new Semaphore(0);public static void main(String[] args) {Barbe bar = new Barbe(mutex, customer, barber);Thread b1 = new Thread(bar);b1.start();int n = 10;for(int i=0;i<n;i++) {Customer cus = new Customer(i, mutex, customer, barber);Thread t = new Thread(cus);t.start();System.out.println("顾客: " + i + " 等待理发");try {Thread.sleep((long)(Math.random() * 2000));}catch(InterruptedException e) {e.printStackTrace();}}}}

监控器实现的是生产者消费者

什么是监控器?

监控器每次只能由一个线程访问;对共享变量的访问只能发生在监控器内定义的过程中。

import java.util.Vector;class CP{Vector pool;int product = 0; // 产品数量public static int EMPTY = 0;public static int FULL = 25;public CP() {pool = new Vector();}public synchronized void produce() {try {if(pool.size() == FULL)wait();product++;pool.addElement(new Integer(product));// 把产品放到产品池中System.out.println("Produce: " + product);if(pool.size() == EMPTY + 1)notify();}catch(InterruptedException e) {e.printStackTrace();}}public synchronized void consume() {try {if(pool.size() == EMPTY)wait();System.out.println("Consume: " + pool.firstElement().toString());pool.removeElementAt(0);if(pool.size() == FULL - 1)notify();}catch(InterruptedException e) {e.printStackTrace();}}
}class Producer extends Thread{CP cp;public Producer(CP cp) {super();this.cp = cp;}public void run() {while(true) {cp.produce();//模拟做其他工作try {Thread.sleep((long)(Math.random()* 1000));}catch(InterruptedException e) {e.printStackTrace();}}}
}class Consumer extends Thread{CP cp;public Consumer(CP cp) {super();this.cp = cp;}public void run() {while(true) {cp.consume();//模拟做其他事情try {Thread.sleep((long)(Math.random() * 1000));}catch(InterruptedException e) {e.printStackTrace();}}}
}public class ProducerConsumer{public static void main(String[] args) {CP cp = new CP();Producer producer = new Producer(cp);Consumer consumer = new Consumer(cp);producer.start();consumer.start();}
}

java实现的PV操作经典例子:读者写者、贪睡的理发师、生产者消费者。相关推荐

  1. 几个java实现的PV操作经典例子:读者写者、贪睡的理发师、生产者消费者

    其中读者写者和贪睡的理发师使用的Semaphore类:生产者消费者使用的是管程. 读者写者: class Semaphore {int value;public Semaphore(int v){th ...

  2. JAVA入门基础进阶(十四)—— 实现多线程、线程同步、生产者消费者

    文章目录 1.实现多线程 1.1简单了解多线程[理解] 1.2并发和并行[理解] 1.3进程和线程[理解] 1.4实现多线程方式一:继承Thread类[应用] 1.5实现多线程方式二:实现Runnab ...

  3. PV操作经典例题——吃水果

    例1:桌上有一个盘子,每次只能放一个水果,妈妈向盘中放苹果和橘子,儿子专等吃盘里的橘子,女儿专等吃盘里的苹果.只要盘子空,妈妈可向盘中放水果,仅当盘中有自己需要的水果时,儿子或女儿可从中取出,请给出他 ...

  4. 【操作系统】PV 操作经典例题---三个进程之间的同步

    问题: 总共有 读入.执行.打印 三个进程,试用PV操作描述读入B1打印B2的同步过程. 问题解读: 这个问题就是说了这样一件事:一个输入B1,被操作之后,成为B2,将B2打印.怎样用PV操作来说这件 ...

  5. PV 操作经典例题---三个进程之间的同步

    问题: 总共有 读入.执行.打印 三个进程,试用PV操作描述读入B1打印B2的同步过程. 问题解读: 这个问题就是说了这样一件事:一个输入B1,被操作之后,成为B2,将B2打印.怎样用PV操作来说这件 ...

  6. java中的pv操作,PV操作简单理解

    进程通常分为就绪.运行和阻塞三个工作状态.三种状态在某些条件下可以转换,三者之间的转换关系如下: 进程三个状态之间的转换就是靠PV操作来控制的.PV操作主要就是P操作.V操作和信号量.其中信号量起到了 ...

  7. p,v操作例题解析--读者-写者问题--誊抄问题——睡眠理发师问题

    问题1:读者写者问题 层次1:只有读者,最多允许有k个读者,用p,v操作写出程序. int main() {int rspace = k;cobeginread_1();read_2();--read ...

  8. PV操作经典例题——哲学家进餐问题

    哲学家进餐问题: 五个哲学家共用一张圆桌,分别坐在周围的五张椅子上,在桌子上有五只碗和五只筷子,他们的生活方式是交替地进行思考和进餐.平时,一个哲学家进行思考,饥饿时便试图取用其左右最靠近他的筷子,只 ...

  9. PV操作经典例题——司机与售票员的进程同步问题

    例1: 司机的活动: 启动车辆, 正常行车, 到站停车. 售票员活动: 关车门, 售票, 开车门. 注意:当发车时间到,售票员关好车门后,司机才能启动车辆,售票员才开始售票. 当到站时,司机停稳车后, ...

最新文章

  1. SSClone非ARP会话劫持原理分析
  2. Netflix:通过可视化和统计学改进用户QoE
  3. windows系统如何进入环境变量
  4. mysql 本地登录失败 - 已授权
  5. 面对key数量多和区间查询低效问题:Hash索引趴窝,LSM树申请出场
  6. 计算机网络复习题大全(各种题型)
  7. 【网络文件共享】04、rsync基础
  8. 问题解决:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'
  9. 阿里云AIoT造物秘籍●开放下载
  10. 猎人华为单机离线版(一键启动增强版+扩展工具箱2022) | 猎人维修大师免加密狗单机永久版 | 华为线刷工具(MRT HW Flash Tool) | 华为工具(MRT HW Tool_V3.3)
  11. SpringBoot中调用第三方接口的三种方式
  12. c语言求开平方标准库函数,c语言如何求平方根 C语言中开平方函数是什么?
  13. linux 从设备 spi,在Linux 4.9设备树中添加SPI slave设备rapbery pi
  14. 西门子bop20显示电流_SIEMENS/西门子BOP20基本操作员面板使用方法说明
  15. 如何解决外边距重叠问题
  16. Ventoy多镜像+防毒全能U盘工具箱
  17. 展锐Camera open failure log解析程序
  18. 韭菜简史:快招加盟的致富骗局
  19. java 不同包 调用_java中不同包之间的调用
  20. 电子计算机开关及清屏键,计算机清屏键是什么

热门文章

  1. 富文本的内容怎么转换格式
  2. 加密狗原理介绍(转)
  3. pro坚果android耗流量,深度使用坚果Pro3一个月,憋了一肚子话,不吐不快​
  4. 市场调研工具—铺货率调查
  5. C语言动态规划法解决0/1背包问题(详细解答)
  6. ARM架构与x86架构的区别
  7. 复选框checkbox如何一直选中,不能去掉勾选
  8. 0基础linux运维教程 sersync介绍
  9. 502报错 网络异常
  10. 使用c++通过opencv库进行图片的保存