生产者消费者
生产者线程,消费者线程
共享数据
Object类的等待和唤醒方法
void wait()导致当前线程等待,直到另一个贤臣调用该对象的notify()方法或notifyAll()方法
void notify()唤醒正在等待对象监视器的单个线程
void notifyAll()唤醒正在等待对象监视器的所有线程
123
包含的类
奶箱类(Box):定义一个成员变量,表示第几瓶奶,提供存储牛奶和获取牛奶的操作
public class Box {
//表示第几瓶奶
private int index = 0;
public void get(){
for(int i=1; i<5; i++){
index++;
System.out.println("存储第"+ index +"瓶奶");
}
}
public void input(){
for(int i=1; i<5; i++){
System.out.println("获取第"+ index +"瓶奶");
index--;
}
}
}
生产者类(Produccer):实现Runnable接口,重写run()方法,调用存储牛奶的操作
public class Producer implements Runnable{
private Box box;
public Producer(Box box) {
this.box = box;
}
@Override
public void run() {
box.get();
}
}
消费者类(Customer):实现Runnable接口,重写run()方法,调用获取牛奶的操作
public class Customer implements Runnable{
private Box box;
public Customer(Box box) {
this.box = box;
}
@Override
public void run() {
box.input();
}
}
测试类(BoxDemo):里面有main方法,创建奶箱对象,把奶箱对象作为构造方法参数传递,在这个类中调用存储牛奶的方法;创建消费者对象,奶箱对象作为构造方法参数传递;创建两个线程对象,分别把生产者对象和消费者对象作为构造方法参数传递;启动线程
public class BoxDemo {
public static void main(String[] args){
Box box = new Box();
Producer p = new Producer(box);
Customer c = new Customer(box);
Thread t1 = new Thread(c);
Thread t2 = new Thread(p);
t1.start();
t2.start();
}
}
生产牛奶操作
如果有牛奶等待消费,定义牛奶的状态
如果没有牛奶生产牛奶
生产牛奶完毕后,修改奶箱状态
private boolean state;
public void put(int index){
if(state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.index = index;
System.out.println("存储第"+ index +"瓶奶");
state = true;
}
消费牛奶的操作
如果没有牛奶,等待生产
如果有牛奶,就消费牛奶
消费完毕后,修改奶箱状态
public void get(){
if(!state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("获取第"+ index +"瓶奶");
state = false;
}
wait()需要使用同步关键字
public synchronized void put(int index)
public synchronized void get()
唤醒其他等待的线程:notifyAll()操作
public synchronized void put(int index){
if(state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.index = index;
System.out.println("存储第"+ index +"瓶奶");
state = true;
notifyAll();
}
public synchronized void get(){
if(!state){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("获取第"+ index +"瓶奶");
state = false;
notifyAll();
}