zoukankan      html  css  js  c++  java
  • 模拟抢购

    package com.aaa.thread.Test;
    
    public class Test1 implements Runnable {
        private int num=10;
        private int count=0;
    
        //必须使用start方法来进行run方法的运行
        @Override
        public void run() {
            while (true){
                if (!buy()){
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //synchronized 不同步的
        public synchronized boolean buy(){
            if (num<=0){
                return false;
            }
    
            num--;
            count++;
    
            System.out.println(Thread.currentThread().getName() + "抢购到了衣服" + "还剩" + num + "");
            return true;
        }
    //单线程安全无比
        public static void main(String[] args) {
            Test1 t = new Test1();
            Thread t1 = new Thread(t,"One");
            Thread t2 = new Thread(t,"Two");
            Thread t3 = new Thread(t,"Three");
            Thread t4 = new Thread(t,"Four");
            Thread t5 = new Thread(t,"Five");
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
    
        }
    }
  • 相关阅读:
    P1443 马的遍历
    P1747 好奇怪的游戏
    蜀绣
    Five hundred miles
    如果没有你
    Yellow
    流星

    深入理解计算机中的 csapp,h和csapp.c
    可迭代的集合类型使用foreach语句
  • 原文地址:https://www.cnblogs.com/fanqiexin/p/11124282.html
Copyright © 2011-2022 走看看