package com.ccl.thread;
public class ProducerCustomer {
/**
* @author changlun.cheng
* @param args
* @see Product/Producer/Customer/Store 生产者与消费者
*/
public static void main(String[] args) {
Store s = new Store();
for (int i = 0; i < 4; i++) {
Producer pi = new Producer(s, i);
Thread tp = new Thread(pi);
tp.start();
Customer c = new Customer(s);
Thread tc = new Thread(c);
tc.start();
}
}
}
生产者类:
package com.ccl.thread;
public class Producer implements Runnable {
public Store s;
public int rank;
public Producer(Store s, int rank) {
this.rank = rank;
this.s = s;
System.out.println("new a producer.");
}
@Override
public void run() {
for (int i = 1; i < 41; i++) {
make(i + rank * 40);
}
}
private void make(int id) {
Product p = new Product(id);
s.push(p);
try {
Double d = Math.random() * 500;
Thread.sleep(d.longValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
产品类:
package com.ccl.thread;
public class Product {
public int Id;
public Product(int id) {
Id = id;
System.out.println("new a product . this is id: " + Id);
}
}
消费者类:
package com.ccl.thread;
public class Customer implements Runnable {
public Store s;
public Customer(Store s) {
this.s = s;
System.out.println("come on a customer.");
}
@Override
public void run() {
for (int i = 0; i < 40; i++) {
eat();
}
}
private void eat() {
Product p = s.pop();
System.out.println("customer eat " + p.Id);
try {
Double d = Math.random() * 1000;
Thread.sleep(d.longValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
仓库类:
package com.ccl.thread;
public class Store {
private int index = 0;
public Store() {
}
private Product[] array = new Product[10];
public synchronized void push(Product p) {
while (index == array.length) {
try {
this.wait();
System.out.println("a producer wait.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
array[index] = p;
index++;
}
public synchronized Product pop() {
while (index == 0) {
try {
this.wait();
System.out.println("a customer wait.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return array[index];
}
}
分享到:
相关推荐
生产者与消费者实验报告生产者与消费者实验报告生产者与消费者实验报告生产者与消费者实验报告
生产者与消费者生产者与消费者生产者与消费者生产者与消费者生产者与消费者
生产者与消费者进程共享一个大小固定的缓冲区。其中,一个或多个生产者生产数据,并将生产的数据存入缓冲区,并有一个或多个消费者从缓冲区中取数据。 2、 系统设计: 系统的设计必须要体现进程之间的同步关系,...
生产者与消费者实验代码 关于进程的互斥访问 关于临界区的用处
用c语言 pv操作解决生产者与消费者问题
编写程序,运用Win32Api实现生产者与消费者使用缓冲区完成生产者与消费者的关系。模拟生产者和消费者的处理过程,程序中演示同步与互斥的关系。
操作系统生产者与消费者课程设计报告
模拟生产者与消费者问题,生产者和消费者同时向一个共享缓冲区放进和取出产品。
C#编写的有关操作系统中生产者与消费者问题的实例,画面美观,生动形象的描绘了生产者与消费者之间的关系,代码部分简介易懂。
生产者与消费者问题(操作系统)
通过实验模拟生产者与消费者之间的关系,了解并掌握他们之间的关系及其原理。由此增加对进程同步的问题的了解。 实验要求: 每个进程有一个进程控制块(PCB)表示。进程控制块可以包含如下信息:进程
进程同步实验——生产者与消费者问题算法实现
C++ 用多方程解决生产者与消费者的问题
大连理工大学操作系统大作业, 进程同步与互斥 生产者与消费者问题
利用Java多线程实现的操作系统的生产者与消费者算法,主要用到了线程的同步,等待与唤醒操作。
Java生产者与消费者Demo
linux下的生产者与消费者实例,C实现,有注释,翻译的某个window下生产者与消费者的例子
利用Windows提供的API函数,编写程序,解决生产者与消费者问题,实现进程的互斥与同步。
上课实验用VC++做的操作系统实验之进程的互斥与同步(生产者与消费者问题),内含实验报告,希望对大家有帮助