多线程模拟例题

创建一个商品类, 商品有编号, 价格, 生产日期属性,商品的编号不能重复.创建一个仓库类, 用户储存商品, 仓库类中使用Map集合, 将商品的编号当作是key,仓库有存储和取出的方法,创建两个工人和两个消费者, 工人生产商品, 消费者消费商品, 永不停止如果消费者消费时没有商品了, 就打印一句话:"快点生产呀", 然后休息1秒钟

商品类

import java.util.Date;

public class Commodity {
    private int num;
    private int price;
    private  Date date = new Date();
    public Commodity(int num, int price, Date date) {
        super();
        this.num = num;
        this.price = price;
        this.date = date;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    @Override
    public String toString() {
        return " 商品[编号:" + num + ", 价格:" + price + ", 日期:" + date + "]";
    }
    
    
}

仓库类


import java.util.HashMap;

public class Warehouse {
    static HashMap<Integer, Commodity> map = new HashMap<>();
    
    public static synchronized void cun(Commodity c){
        map.put(c.getNum(), c);
    }
    public static synchronized Commodity qu(){
        for(Integer i : map.keySet()){
            return map.remove(i);
        }
        return null;        
    }
    
}

员工


import java.util.Date;
import java.util.Random;

public class Gongren extends Thread {
    static int num =0;
    public void run() {
        Warehouse wa = new Warehouse();
        Random ra = new Random();
        Date date = new Date();
     synchronized (Class.class) {

         while(true){
            num++;
            Commodity co = new Commodity(num, ra.nextInt(21)+20, date);
            wa.cun(co);
            System.out.println(Thread.currentThread().getName()+"做了一个"+co);
            
         }

      }
    }    
}


消费者

public class People extends Thread{
    public void run (){
        
        
        while(true){
            Commodity co = Warehouse.qu();
            if(co==null){
                System.out.println("快点生产吧");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }                
            }else{
                System.out.println(this.getName()+"买了一个"+co);
            }            
        }
    }
}

测试


public class Test5 {
    public static void main(String[] args) {
        Gongren g1 = new Gongren();
        Gongren g2 = new Gongren();
        g1.setName("员工甲");      
        g2.setName("员工乙");
        People p1 = new People();
        People p2 = new People();
        p1.setName("消费者1");
        p2.setName("消费者2");
        g1.start();
        g2.start();
        p1.start();
        p2.start();
        
    }
}

猜你喜欢

转载自blog.csdn.net/mfylove/article/details/81142534