zoukankan      html  css  js  c++  java
  • 线程练习-网络买票

    package cn.BuyTickets;
    //线程类
    public class BuyTickets implements Runnable{
        private int num;
        private int count=10;
        
        @Override
        public void run() {
            while(true) {
                boolean flag = buy();
                if(flag == false) {
                    return;
                }
            }
            
        }
        //synchronized不能放在run方法中,否则只有一人抢票
        synchronized public boolean buy() {
            if(count==0) {
                System.out.println("已无票");
                return false;
            }
            num++;
            count--;
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"抢到了第"+num+"张票,余票"+count+"张");
            if("黄牛党".equals(Thread.currentThread().getName())){
                return false;    
            }
            return true;
        }        
    }
    线程类
    package cn.BuyTickets;
    
    public class Main {
        public static void main(String[] args) {
            BuyTickets bt = new BuyTickets();
            Thread d1 = new Thread(bt,"淘泡泡");
            Thread d2 = new Thread(bt,"张票票");
            Thread d3 = new Thread(bt,"黄牛党");
            d1.start();
            d2.start();
            d3.start();
            
        }
    }
    main方法类

  • 相关阅读:
    js bubbleSort
    关于“ ,”的迷
    移位
    emacs 一些很有用的快捷键
    input&output
    async&await
    用dbforge调试procedure
    开发中常用的工具
    用Firefox的debugger来调试JavaScript
    Hibernate映射关系配置
  • 原文地址:https://www.cnblogs.com/lev1/p/11305833.html
Copyright © 2011-2022 走看看