首页 > 其他分享 >多线程练习

多线程练习

时间:2022-12-09 18:44:06浏览次数:29  
标签:10 price 练习 num void new 多线程 public

 Map<String, Integer> totalStock = new HashMap<>();
    AtomicInteger total = new AtomicInteger();
    private List<Car> carList = new ArrayList<>();

    public void testSale() {
        produceCar();
        for (; ; ) {
            if (total.get()>0) {
                sleep(TimeUnit.MILLISECONDS,200);
                saleCar();
            } else {
                System.out.println("所有库存都卖完了,快点进货吧!");
                break;
            }
        }
    }

    private void saleCar() {
        new Thread(() -> carList.forEach(car -> car.sale(new Custom(RandomUtil.randomString(10),
                RandomUtil.randomDouble(0, 1000000.00)))), "小红").start();

        new Thread(() -> carList.forEach(car -> car.sale(new Custom(RandomUtil.randomString(10),
                RandomUtil.randomDouble(0, 1000000.00)))), "小张").start();

        new Thread(() -> carList.forEach(car -> car.sale(new Custom(RandomUtil.randomString(10),
                RandomUtil.randomDouble(0, 1000000.00)))), "小明").start();

        new Thread(() -> carList.forEach(car -> car.sale(new Custom(RandomUtil.randomString(10),
                RandomUtil.randomDouble(0, 1000000.00)))), "小花").start();

    }

    private void produceCar() {
        System.out.println("开始进购汽车....");
        carList.add(new Car("高尔夫", 10, 129888, 0.94f));
        totalStock.put("高尔夫", 10);
        total.addAndGet(10);
        System.out.println("进购高尔夫 10");
        carList.add(new Car("Polo", 10, 90998, 0.9f));
        totalStock.put("Polo", 10);
        total.addAndGet(10);
        System.out.println("进购Polo 10");
        carList.add(new Car("迈腾", 40, 186898, 0.9f));
        totalStock.put("迈腾", 40);
        total.addAndGet(40);
        System.out.println("进购迈腾 40");
        carList.add(new Car("途观", 30, 199088, 0.91f));
        totalStock.put("途观", 30);
        total.addAndGet(30);
        System.out.println("进购途观 30");
        System.out.println("共进购" + totalStock + "汽车,总库存" + total);
    }

    class Custom {

        String name;
        double capitalFund;

        final List<String> cars = new ArrayList<>();

        public Custom(String name, double capitalFund) {
            this.name = name;
            this.capitalFund = capitalFund;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public double getCapitalFund() {
            return capitalFund;
        }

        public void setCapitalFund(double capitalFund) {
            this.capitalFund = capitalFund;
        }

        public int buyCar(String carName, double carPrice) {

            try {
                double fund = capitalFund - carPrice;
                if (fund >= 0d) {
                    cars.add("品牌:" + carName + ",价格:" + carPrice);
                    System.out.println(name + "买人了一辆" + carName + "剩余资产:" + NumberUtil.roundStr(fund, 2));
                    this.setCapitalFund(fund);
                    TimeUnit.MILLISECONDS.sleep(20);
                    return 1;
                } else {
                    System.out.println(name + "想买人了一辆" + carName + "," +
                            "可是资产不足,总资产:" + NumberUtil.roundStr(capitalFund, 2) + ",需要资产:" + NumberUtil.roundStr(carPrice, 2));
                    return 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        }
    }


    class Car {
        String brandName;
        int num;
        int price;
        double discount;

        public Car(String brandName, int num, int price, double discount) {
            this.brandName = brandName;
            this.num = num;
            this.price = price;
            this.discount = discount;
        }

        public String getBrandName() {
            return brandName;
        }

        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }

        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 double getDiscount() {
            return discount;
        }

        public void setDiscount(double discount) {
            this.discount = discount;
        }

        Lock lock = new ReentrantLock();

        public void sale(Custom custom) {
            lock.lock();
            try {
                if (num > 0) {
                    double price = (this.price * this.discount) + (this.price / 1.17 * 0.1);
                    int r = custom.buyCar(this.getBrandName(), price);
                    if (r > 0) {
                        num--;
                        total.decrementAndGet();
                        totalStock.put(this.brandName, num);
                        System.out.println(Thread.currentThread().getName() + "卖给了" + custom.getName() + "一辆" + this.brandName + "车," + this.brandName + "剩余:" + num);
                        System.out.println("本店库存:" + totalStock + ",total:" + total);
                        TimeUnit.MILLISECONDS.sleep(10);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }

    private void sleep(TimeUnit timeUnit, int time) {
        try {
            timeUnit.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

标签:10,price,练习,num,void,new,多线程,public
From: https://www.cnblogs.com/hlooc/p/16969739.html

相关文章

  • 八校杭州集训练习记录
    八校联考杭州集训!清澄内部私有的题目当然不会被计入。不然就是泄题了是不是。这个标题只是表示一段时期。八校集训时间是2022.11.29-12.16,当然今天才开始记录是因......
  • C++课本的练习题及答案(第六章)
    第六章练习题一、选择题1.下列类的定义中正确的是(   )。(A)classa{intx=0;inty=1;}          (B)classb{intx=0;inty=1;};(C)classc{intx;inty;}     ......
  • 【人工智能 & 机器学习 & 深度学习】基础选择题 61~90题 练习(题目+答案)
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......
  • 6.python-练习定义函数
    defprint_content(content):print(content)defget_sentence_constituent(sentence,constituent):returninput("请输入%s的%s:"%(sentence,constituent))......
  • (29)C#多线程
    使用线程的原因1.不希望用户界面停止响应。2.所有需要等待的操作,如文件、数据库或网络访问需要一定的时间。一个进程的多个线程可以同时运行不同cpu或多核cpu的不同内核上注......
  • python123_第七周练习_程序设计题
    羽毛球计分规则:1.21分制,3局2胜为佳2.每球得分制3.每回合中,取胜的一方加1分4.当双方均为20分时,领先对方2分的一方赢得该局比赛5.当双方均为29分时,先取得30......
  • 高中计算能力提升专项练习
    一、计算下列各式的值:(1)\((-0.6)-\left(-3\frac{1}{4}\right)-\left(+7\frac{2}{5}\right)+2\frac{3}{4}-2\)(2)\(3-\left[(-1)^3-1\right]-|(-2)\div6|\)3(3)......
  • 第八章练习题
    黑盒测试什么叫等价类划分法?它的意义和步骤等价类划分法是将程序的输入域划分为若干个部分,然后从每个部分选区少数代表数据当作测试用例。意义:完备性,无冗余性。步骤:1......
  • 随笔(四)『Java多线程(创建线程方式)』
    1、创建线程方式一:『继承Thread类』/***创建线程方式一:『继承Thread类』*/publicclassThreadTest{publicstaticclassMyThreadextendsThread{......
  • 多线程的原子性,可见性,有序性
    java内存模型定义了主存,工作内存等这些抽象概念,底层对应着cpu寄存器,缓存,cpu指令优化等。由此引出了原子性,可见性,有序性一、原子性保证指令不会受到上下文切换的影响而......