生产者与消费者问题

多线程编程中的一个典型问题是生产者与消费者问题,这是线程同步或者说是线程间通信的一个典型实例。这里再简单复习一下吧。
在这个问题中,有一个生产者负责源源不断地生成产品放入仓库,还一个消费者源源不断地从仓库中提出产品。仓库有一个固定的容量,仓库满的时候生产者的操作要暂时挂起等待仓库有空间时再放入产品,当仓库空的时候,消费者提取产品的工作也会挂起,等待仓库中有产品放入后再继续。因此说,存放产品和提取产品是两个需要同步的操作,或者准确地说:消费者的消费操作和生产者的生产操作是可以同步进行的(并发执行),但同时它们之间又必须通过一定的机制来相互的协调,在某些特殊的时刻,让谁先执行,谁后执行,才能避免出现上述问题。
在java中,这个问题就是通过wait和notify来实现的。注意:wait和notify必须放在同步块中!一般情况是同步块的加锁对象就是wait和notify的从属对象。wait方法将释放当前对象的锁,这样当前线程就被置于block状态(因为当前线程在当前对象上是同步的),以便其他线程可以执行,直到它需要的某个条件由其他线程实现了。而notify方法正是那个实现了某个条件的线程用来通知虚拟机,可以尝试唤醒其他线程了。等到这个线程执行完毕,归还了当前对象的锁,某个被唤醒的线程会得到这个锁,比如说前一个wait的线程,这时候它们条件已经满足,因而可以继续执行下去了。
wait和notify与同步机制的关系: “竞争条件”是指两个以上的线程会因为执行顺序的不同而导致程序变量或是返回值的不同。这样必然会出现错误的结果,这种错误的结果有一种叫法:共享数据的腐蚀。同步机制正是用来解决“竞争条件”问题的。但是仅有同步是不够的,本质上,同步是确保共享数据能被线程安全地访问, 它是从“ 隔离 线程”角度来安排线程的推进的。但是线程除了需要隔离,还需要相互通信,以协调地完成一项工作,这正是wait和notify的作用。以下是Java Theads一书的摘入:

The wait-and-notify mechanism is a synchronization mechanism. However, it is more of a communication mechanism: it allows one thread to communicate to another thread that a particular condition has occurred. The wait-and-notify mechanism does not specify what the specific condition is.

Can the wait-and-notify mechanism be used to replace the synchronized mechanism? Actually, the answer is no; wait-and-notify does not solve the race condition problem that the synchronized mechanism solves. As a matter of fact, wait-and-notify must be used in conjunction with the synchronized lock to prevent a race condition in the wait-and-notify mechanism itself.

下面是生产者与消费者的代码:

Store:仓库类

package producer; import java.util.LinkedList; import java.util.Queue; public class Store { private Queue<String> queue = new LinkedList<String>(); public synchronized String get() { try { System.out.println("Start to get..."); System.out.println("The store's size is " + queue.size()); //NOTE: Here is while NOT if. If there are two consumers, //When a producer set a product to this store, and notified other //threads, one of those two consumers will get lock and go on get production, //but there is a notification too in get method, it may await the other consumer, //that consumer try to get product, however, there's no product at that time! //So, we have to let program check again! while (queue.isEmpty()) { System.out.println("waiting get..."); wait(); } System.out.println("The store's size is " + queue.size()); String product = queue.remove(); System.out.println("End to get..."); notify(); return product; } catch (InterruptedException e) { e.printStackTrace(); return null; } } public synchronized void set(String product) { try { System.out.println("Start to set..."); System.out.println("The store's size is " + queue.size()); while (queue.size() == 3) { System.out.println("waiting set..."); wait(); } System.out.println("The store's size is " + queue.size()); queue.add(product); System.out.println("End to set..."); notify(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Store s = new Store(); Consumer c1 = new Consumer(s); Producer p1 = new Producer(s); Consumer c2 = new Consumer(s); Producer p2 = new Producer(s); Thread t1 = new Thread(c1); Thread t2 = new Thread(p1); Thread t3 = new Thread(c2); Thread t4 = new Thread(p2); t1.start(); t2.start(); t3.start(); t4.start(); } }

Producer:生产者

package producer; import java.util.Random; public class Producer implements Runnable { private Store store; public Producer(Store store) { super(); this.store = store; } @Override public void run() { try { while(true){ store.set("a"); System.out.println(); Thread.sleep(new Random().nextInt(1000)); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Consumer:消费者

package producer; import java.util.Random; public class Consumer implements Runnable{ private Store store; public Consumer(Store store) { super(); this.store = store; } @Override public void run() { try { while(true){ Thread.sleep(new Random().nextInt(1000)); System.out.println(store.get()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

1. 目的: 调试、修改、运行模拟程序,通过形象化的状态显示,使学生理解进程的概念,了解同步和通信的过程,掌握进程通信和同步的机制,特别是利用缓冲区进行同步和通信的过程。通过补充新功能,使学生能灵活运用相关知识,培养创新能力。 2. 内容及要求: 1) 调试、运行模拟程序。 2) 发现并修改程序中不善的地方。 3) 修改程序,使用随机数控制创建生产者消费者的过程。 4) 在原来程序的基础上,加入缓冲区的写互斥控制功能,模拟多个进程存取一个公共缓冲区,当有进程正在写缓冲区,其他要访问该缓冲区的进程必须等待,当有进程正在读取缓冲区,其他要求读取的进程可以访问,而要求写的进程应该等待。 5) 成1)、2)、3)功能的,得基本分,成4)功能的加2分,有其它功能改进的再加2分 3. 程序说明:   本程序是模拟两个进程,生产者(producer)和消费者(Consumer)工作。生产者每次产生一个数据,送入缓冲区中。消费者每次从缓冲区中取走一个数据。缓冲区可以容纳8个数据。因为缓冲区是有限的,因此当其生产者进程应该等待,而空消费者进程应该等待;当生产者向缓冲区放入了一个数据,应唤醒正在等待的消费者进程,同样,当消费者取走一个数据后,应唤醒正在等待的生产者进程。就是生产者消费者之间的同步。   每次写入和读出数据,都将读和写指针加一。当读写指针同样,又一起退回起点。当写指针指向最后生产者就等待。当读指针为零,再次要读取的消费者也应该等待。 为简单起见,每次产生的数据为0-99的整数,从0开始,顺序递增。两个进程的调度是通过运行者使用键盘来实现的。 4. 程序使用的数据结构 进程控制块:包括进程名,进程状态和执行次数。 缓冲区:一个整数数组。 缓冲区说明块:包括类型,读指针,写指针,读等待指针和写等待指针。 5. 程序使用说明   启动程序后,如果使用'p'键则运行一次生产者进程,使用'c'键则运行一次消费者进程。通过屏幕可以观察到两个进程的状态和缓冲区变化的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值