在多线程的开发过程之中最为著名的案例就是生产者与消费者操作,该操作的主要流程如下
- 生产者负责信息内容的生产:
- 每当生产者生产完成一项完整的信息之后,消费者要从这里面取走信息:
- 如果生产者没有生产完,则消费者要等待他生产完成,如果消费者还没有对信息进行消费,则生产者要等待消费者对信息消费完成之后再生产
程序的基本实现
可以将生产者与消费者定义为两个独立的线程类对象,但是对于现在生产的数据 可以使用如下的组成
- 数据一:title=cirry,content=帅哥
- 数据二:title=winnie,content=美女
既然生产者与消费者是两个独立的线程,那么这两个独立的线程之间就需要一个数据的保存集中点,那么可以单独的定义一个Message类
范例:
通过整个代码的执行你会发现此时有两个问题:
- 问题一:数据不同步了
- 问题二:生产一个取走一个,但是发现有了重复生产和重复取出问题。
解决数据同步问题
如果想要解决问题, 首先要解决的就是数据同步的处理问题,如果要想解决数据同步最简的就是用synchronize同步代码块或同步方法,于是这个时候对于同步的处理就可以直接在Message类中完成。
范例:解决同步操作问题
在进行同步处理的时候肯定需要有一个同步的处理对象,那么此时肯定要将同步操作交由Message类处理最合适。这个时候发现数据已经可以正常的保持一致了,但是对于重复操作的问题依然存在。
线程等待与唤醒
如果仙子要想解决生产者与箱费这的问题,那么最好的解决方案就是使用等待与唤醒机制。而对于等待与唤醒的机制主要依靠的是Object类中提供的方法处理:
- 等待机制:
- 死等:public final void wait() throws InterruptedException ;
- 设置等待时间:public final void wait(long timeout) throws InterruptedException ;
- 设置等待时间 :public final void wait(long timeout, int nanos) throws InterruptedException;
- 唤醒第一个等待线程:public final void notify();
- 唤醒全部等待线程:public final void notifyAll();
如果此时有若干个等待线程的话,那么notify()表示的是唤醒第一个等待的,而其他的线程继续等待。而notifyAll()表示会唤醒所有等待的线程,哪个线程的优先级高就有可能先执行。
对于当前的问题主要的解决应该通过Message类来解决。
范例:
执行结果:
cirry - 帅哥
winnie - 美女
…
这个方案就是多线程开发过程之中最原始的处理方案,整个的等待,同步,唤醒机智都是由开发者自行通过原生代码实现控制。