1.产品
package 生产者消费者;
public class 产品 {
private Integer id;
public 产品(Integer id){
this.id = id;
}
@Override
public String toString() {
return "产品{"+"id="+id+'}';
}
}
2.仓库
package 生产者消费者;
import java.util.ArrayList;
import java.util.List;
public class 仓库 {
private int max = 10;//仓库最大容量10
private List<产品> list = new ArrayList<>();//这就是那个仓库
public synchronized void 出库(){
if (list.size()==0){
//缺货
System.out.println("缺货");
try{
wait();//让线程等待
}catch(Exception e){
System.out.println(e.getMessage());
}
}
产品 c = list.get(0);
list.remove(0);
System.out.println("出库:"+c);
notify();//唤醒 入库的wait
}
public synchronized void 入库(产品 c){
if (list.size()==max){
//仓库满
System.out.println("溢出");
try{
wait();//让线程等待
}catch(Exception e){
System.out.println(e.getMessage());
}
}
list.add(c);
System.out.println("入库:"+c);
notify();//唤醒 出库的wait
}
}
3.生产者
package 生产者消费者;
public class 生产者 extends Thread{
private 仓库 ck;
public 生产者(仓库 ck) {
this.ck = ck;
}
@Override
public void run() {
for (int i = 1; i < 21; i++) {
产品 c = new 产品(i);
ck.入库(c);
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
4.经销商
package 生产者消费者;
public class 经销商 extends Thread{
private 仓库 ck;
public 经销商(仓库 ck) {
this.ck = ck;
}
@Override
public void run() {
for (int i = 1; i < 21; i++) {
ck.出库();
try{
Thread.sleep(3000);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
5.测试
package 生产者消费者;
public class Test {
public static void main(String[] args) {
仓库 ck = new 仓库();
生产者 scz = new 生产者(ck);
经销商 jxs = new 经销商(ck);
scz.start();
jxs.start();
}
}