在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发
当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者
处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费
者就必须等待生产者。为了解决这种生产消费能力不均衡的问题,所以便有了生产者和消
费者模式。
生产者/消费者模式的作用
- 支持并发
- 解耦
- 支持忙闲不均
编码体现
public class Basket {
private volatile Object obj = null; // 利用volatile保证可见性
public synchronized void produce(Object obj) {
while (this.obj != null) {
try {
// this.wait();// 当前线程进入minitor的waitSet中
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.obj = obj;
this.notifyAll(); // 唤醒处于waitSet中的所有线程
System.out.println("生产了一个对象:" + obj);
}
public synchronized void consume() {
while (obj == null)
try {
// this.wait();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费了一个对象:" + obj);
this.obj = null;
this.notifyAll();
}
}
public class Consumer implements Runnable {
private Basket resource = null;
public Consumer(Basket resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 20; i++) {
resource.consume();
}
}
}
public class Producer implements Runnable {
private Basket resource = null;
public Producer(Basket resource) {
this.resource = resource;
}
public void run() {
for (int i = 0; i < 20; i++) {
Object obj = new Date();
resource.produce(obj);
}
}
}
public class Test {
public static void main(String[] args) {
Basket resource = new Basket();
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
}
}
wait和notify/notifyAll的用法
调用wait/notify之类的方法要求必须在当前线程对象内部,例如synchronized方法中
- 当线程执行wait()时,会把当前的锁释放,然后让出CPU,进入等待状态。不能更改为sleep,因为sleep不会释放锁
- 当执行notify/notifyAll方法时,会唤醒一个处于等待该对象锁的线程,然后继续往下执行,直到执行完退出对象锁锁住的区域(synchronized修饰的代码块)后再释放锁。