简单的生产者消费者问题
box
点击查看代码
package it_07;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Box {
private int milk;
private boolean state = false;
private Lock lock = new ReentrantLock();
public synchronized void put(int milk){
//如果有产品那就等待消费
if(state){
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//没有就生产
this.milk = milk;
System.out.println("生产者生产了第"+milk+"瓶");
//修改状态
state=true;
//唤醒其他等待的线程
notifyAll();
}
public synchronized void get(){
//如果没有产品就等待
if(!state) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//有就消费
System.out.println("消费者获得了第"+milk+"瓶");
//修改状态
state = false;
//唤醒其他等待的线程
notifyAll();
}
}
点击查看代码
package it_07;
public class Producer implements Runnable{
private Box box;
public Producer(Box box) {
this.box=box;
}
@Override
public void run() {
for(int i=1;i<=5;i++){
box.put(i);
}
}
}
点击查看代码
package it_07;
public class Customer implements Runnable{
private Box box;
public Customer(Box box) {
this.box=box;
}
@Override
public void run() {
while(true){
box.get();
}
}
}
点击查看代码
package it_07;
public class Demo1 {
public static void main(String[] args) {
//创建box,共享数据区
Box box = new Box();
//创建生产者对象
Producer producer = new Producer(box);
//创建消费者对象
Customer customer = new Customer(box);
Thread p = new Thread(producer);
Thread c = new Thread(customer);
p.start();
c.start();
}
}