java多线程生产者和消费者问题
描述
有一个车库,大小为5,当车库满了的时候,生产者不能再往里生产,当车库空了的时候生产者不能再买车。当有生产者往里放车的时候消费者不能买车,当消费者买车的时候,生产者不能生产车。
public class test1{
public static void main(String[] args) throws Exception {
Car car=new Car();
Producer producer=new Producer(car);
Customer customer=new Customer(car);
for(int i=0;i<10;i++) {
new Thread(producer,"生产者"+i).start();;
}
for(int j=0;j<3;j++){
new Thread(customer,"消费者"+j).start();;
}
}
}
class Car{
public final static int size=5;
public static int pre=0;
public synchronized void produce() {
if(Car.pre<Car.size) {
Car.pre++;
System.out.println(Thread.currentThread().getName()+"生产了一辆车,现有"+Car.pre);
}else {
System.out.println("车库满了");
}
}
public synchronized void buy() {
if(Car.pre>0) {
Car.pre--;
System.out.println(Thread.currentThread().getName()+"买了一辆车,现有"+Car.pre);
}else {
System.out.println("车库空了");
}
}
}
class Producer implements Runnable{
private Car car=null;
public Producer(Car car) {
this.car=car;
}
public void run() {
try {
Thread.sleep(1000);
car.produce();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Customer implements Runnable{
private Car car=null;
public Customer(Car car) {
this.car=car;
}
public void run() {
try {
Thread.sleep(1000);
car.buy();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}