- 生产者消费者问题,也称为有限缓冲问题,是一个多线程同步问题的经典案例。该问题描叙了俩个共享固定大小缓冲区的线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。生产者的主要作用是生产一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者不会在缓冲区中空时消耗数据
- 要解决该问题,就必须让生产者在缓冲区满时休眠(要么干脆就放弃数据),等到下次消费者消耗缓冲区中的数据时,生产者才能被唤醒,开始往缓冲区添加数据。同样,也可以让消费者在缓冲区空时进入休眠,等到生产者往缓冲区添加数据之后,再唤醒消费者。通常常用的方法有信号灯法、管程等。如果解决方法不够完善,则容易出现死锁的情况。出现死锁时,俩个线程都会陷入休眠,等待对方唤醒自己
例子;演电影看电影(生产消费者模式)
共享资源Movie
package com.txr.thread.pro;
/**
* 一个场景,共同的资源
* 生产者消费者模式信号灯法
* wait()会释放锁,sleep()不释放锁
* notify()/notifyAll():唤醒
* @author Administrator
*
*/
public class Movie {
private String pic;
//信号灯 flag = true --->生产者生成产,消费者等待,生产完成后通知消费
//flag = false ---->消费者消费,生产者等待,消费完后通知生产
private boolean flag=true;
/**
* 播放
* @param pic
*/
public synchronized void play(String pic)
{
if(!flag){
//生产者等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//开始生产
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//生产完毕
this.pic=pic;
System.out.println("生产了:"+pic);
//通知消费
this.notify();
//生产者停下
this.flag=false;
}
public synchronized void watch()
{
if(flag){
//消费者等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//开始消费
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//消费完毕
System.out.println("消费了"+pic);
//通知生产
this.notify();
//消费停止
this.flag=true;
}
}
生产者:演员
package com.txr.thread.pro;
/**
* 生产者
* @author Administrator
*
*/
public class Player implements Runnable{
private Movie m;
public Player(Movie m)
{
this.m=m;
}
@Override
public void run() {
for(int i=0;i<20;i++)
if(i%2==0)
m.play("左青龙");
else
m.play("右白虎");
}
}
消费者:观众
package com.txr.thread.pro;
/**
* 消费者
* @author Administrator
*
*/
public class watcher implements Runnable{
private Movie m;
public watcher(Movie m) {
this.m=m;
}
@Override
public void run() {
for(int i=0;i<20;i++)
m.watch();
}
}
测试:
package com.txr.thread.pro;
public class App {
public static void main(String[] args) {
//共同的资源
Movie m=new Movie();
//多线程
Player p=new Player(m);
watcher w=new watcher(m);
new Thread(p).start();
new Thread(w).start();
}
}