生产者-消费者模式是多线程并发协作的经典案例。
生产者-消费者问题包含两类的线程, 其中生产者线程用于生产数据,消费者线程用于消费数据。为了解耦生产者和消费者之间的关系,通常采用共享内存的方式(共享数据区域)。生产者只需要把生产的数据放到共享数据区域,而不需要关心消费者的行为。消费者只需要到共享数据区域取数据,而不需要关心生产者的行为。共享数据区域应该要具备以下线程并发协作的功能。
如果共享数据区域满了,阻塞生产者继续生产数据放入其中。
如果共享数据区域空了,阻塞消费者继续消费数据。
JAVA中可以采用三种方式实现:
1.用synchronized对存储加锁,然后用object原生的wait() 和 notify()做同步。
2.用concurrent.locks.Lock,然后用condition的await() 和signal()做同步。
3.直接使用concurrent.BlockingQueue。
(4.使用PipedInputStream/PipedOutputStream。)
(5.使用信号量semaphore。)
1.Object的wait/notify的消息通知机制:
public class Productor_customer_syn {
static private Object key = new Object();//object锁
private int c = 0; //初始容量
private int m = 5;//最大储量
public static void main(String[] args) {
// TODO Auto-generated method stub
Productor_customer_syn pc = new Productor_customer_syn();
while(true) {
new Thread(pc.new Productor()).start();
new Thread(pc.new Customer()).start();
}
}
//生产者类
class Productor implements Runnable{
@Override
public void run() {
try {
Thread.sleep(1000);//减缓速度,观察效果更明显
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(key) { //加锁
while(c>=m)
try {
key.wait();//c满等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c++;//存入
System.out.println("生产"+c);
key.notifyAll();//唤醒锁
}
}
}
//消费者类
class Customer implements Runnable{
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(key) {
while(c<=0)
try {
key.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c--;
System.out.println("消费"+c);
key.notifyAll();
}
}
}
}
2.用concurrent.locks.Lock,然后用condition的await() 和signal()做同步。
import java.util.concurrent.locks.*;
public class Productor_customer_lock {
private int c = 0;
static private int m = 10;
private final Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition(); //生产者Condition
private Condition condition_cos = lock.newCondition(); //消费者Condition
public static void main(String[] args) {
// TODO Auto-generated method stub
Productor_customer_syn pc = new Productor_customer_syn();
for (int i = 1; i <= 5; i++) {
new Thread(pc.new Productor()).start();
new Thread(pc.new Customer()).start();
}
}
class Productor implements Runnable{
@Override
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lock.lock();
try {
while(c>=m)
try {
condition_pro.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
c++;
System.out.println("生产"+c);
condition_cos.signalAll();
}
finally {
lock.unlock();
}
}
}
class Customer implements Runnable{
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lock.lock();
try {
while(c<=0)
try {
condition_cos.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
c--;
System.out.println("消费"+c);
condition_pro.signalAll();
}finally {
lock.unlock();
}
}
}
}
3.直接使用concurrent.BlockingQueue
阻塞队列可以借助它本身的性质实现生产者/消费者模型。当一个线程对已经满了的阻塞队列进行入队操作时会阻塞,除非有另外一个线程进行了出队操作,当一个线程对一个空的阻塞队列进行出队操作时也会阻塞,除非有另外一个线程进行了入队操作。所以阻塞队列本身就可以完成生产者/消费者模型。
public class Demo2 {
private int count = 0;
private BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
public static void main(String[] args) {
Demo2 demo2 = new Demo2();
for (int i = 1; i <= 5; i++) {
new Thread(demo2.new Producer(), "生产者-" + i).start();
new Thread(demo2.new Consumer(), "消费者-" + i).start();
}
}
class Producer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
try {
queue.put(1);
count++;
System.out.println("生产者 " + Thread.currentThread().getName() + " 总共有 " + count + " 个资源");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
queue.take();
count--;
System.out.println("消费者 " + Thread.currentThread().getName() + " 总共有 " + count + " 个资源");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}