操作系统 --管程Monitor(九)
资料:Monitor(管程)是什么意思?Java中Monitor(管程)的介绍
1、管程的定义
系统中的各种硬件资源和软件资源,均可用数据结构抽象地描述其资源特性,即用少量信息和对资源所执行的操作来表征该资源,而忽略了它们的内部结构是实现细节。管程是由一组数据和定义在这组数据之上的对这组数据的操作组成的软件模块,者组操作嫩初始化并改变管程中的数据和同步进程。
(个人理解其实就是抽象成一个类,封装了属性和方法,忽略内部的实现细节,简化了方便调用,用了封装和抽象的思想)
2、管程的定义
1、局部于管程的共享结构数据说明(类的属性)
2、对该数据结构进行操作的一组过程(类的方法)
3、对局部于管程的共享数据设置初始值的语句
熟悉面向对象的会联想,管程很像一个抽象类
3、管程的基本特征
1、局部于管程的数据(类的属性)只能被局部于管程的过程方法(类提供的Getter,Setter方法,对外使用)
2、一个进程只有通过调用管程内的过程(类的方法)才能进入管程访问共享数据
3、每次仅允许一个进程在管程内执行某个内部过程
四、Java简单实现
共享资源
/**
* @author zxc
* @date 2019-03-21 13:34
* 共享资源
*/
public class ShareResource {
private String name;
private int num;
private boolean isEmpty = true; //表示共享资源为空
//生产
public synchronized void push(String name, int price) {
try {
//当生产者第一次生产,!isEmpty是false,表示资源为空,跳出循环,生产资源
// !isEmpty是true,表示资源不为空,等待消费者消费
while (!isEmpty) {
this.wait();
}
this.name = name;
this.num = price;
System.out.println("生产-" + this.name + "--" + this.num);
isEmpty = false; //生产资源后,不为空
this.notify(); //唤醒一个消费者
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费
public synchronized void pop() {
try {
//isEmpty为true,表示共享资源为空,等待生产者生产
//isEmpty为false,表示共享资源不为空,跳过循环,消费资源
while (isEmpty) {
this.wait();
}
isEmpty = true;
this.notify();
System.out.println("消费-" + this.name + "--" + this.num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
生产者
/**
* @author zxc
* @date 2019-03-21 13:39
* 生产者
*/
public class Producer implements Runnable {
private ShareResource resource;
public Producer(ShareResource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
resource.push("小爱同学",i);
}
}
}
消费者
/**
* @author zxc
* @date 2019-03-21 13:47
* 生产者
*/
public class Consumer implements Runnable{
private ShareResource resource;
public Consumer(ShareResource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
resource.pop();
}
}
}
测试
/**
* @author zxc
* @date 2019-03-21 13:57
*/
public class Producer_Consumer_Test {
public static void main(String[] args) {
ShareResource resource = new ShareResource();
//开启线程
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
}
}
结果
生产-小爱同学--0
消费-小爱同学--0
生产-小爱同学--1
消费-小爱同学--1
生产-小爱同学--2
消费-小爱同学--2
生产-小爱同学--3
消费-小爱同学--3
---------------
由于交替出现一个生产者和一个消费者,可见实现了消费者和生产者同步,必须在生产者生产后,资源不为空,才可以消费
同时使用synchronized关键字实现了对临界资源的互斥