转载: link.
仓库
package customer_producer;
import java.util.ArrayList;
import java.util.List;
public class Storage {
private static int MAV_VALUE = 100;
private List<Object> list = new ArrayList<>();
public void producer(int num){
synchronized (list){
while(list.size() + num > MAV_VALUE){
System.out.println("暂不生产");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0; i < num; i++){
list.add(new Object());
}
System.out.println("已生产:" + num + " 仓库容量:" + list.size());
list.notifyAll();
}
}
public void consume(int num){
synchronized (list){
while(list.size() < num){
System.out.println("暂不消费");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0; i < num; i++){
list.remove(0);
}
System.out.println("已消费:" + num + " 仓库容量:" + list.size());
list.notifyAll();
}
}
}
生产者
package customer_producer;
public class Producer extends Thread{
private int num;
private Storage storage;
public Producer(Storage storage){
this.storage = storage;
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num = num;
}
public void run(){
storage.producer(getNum());
}
}
消费者
package customer_producer;
public class Customer extends Thread{
private int num;
private Storage storage;
public Customer(Storage storage){
this.storage = storage;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public void run(){
storage.consume(getNum());
}
}
测试
package customer_producer;
public class Test {
public static void main(String[] args) {
Storage storage = new Storage();
Producer producer1 = new Producer(storage);
Producer producer2 = new Producer(storage);
Producer producer3 = new Producer(storage);
Producer producer4 = new Producer(storage);
Customer customer1 = new Customer(storage);
Customer customer2 = new Customer(storage);
Customer customer3 = new Customer(storage);
producer1.setNum(10);
producer2.setNum(20);
producer3.setNum(10);
producer4.setNum(80);
customer1.setNum(50);
customer2.setNum(20);
customer3.setNum(20);
customer1.start();
customer2.start();
customer3.start();
producer1.start();
producer2.start();
producer3.start();
producer4.start();
}
}