zoukankan      html  css  js  c++  java
  • 线程不安全

    public class UnsafeBuyTicket {
        public static void main(String[] args) {
            BuyTicket station = new BuyTicket();
    
            new Thread(station,"苦逼的我").start();
            new Thread(station,"牛逼的你").start();
            new Thread(station,"可恶的黄牛党").start();
        }
    
    }
    class BuyTicket implements Runnable{
        //
        private int ticketNnums = 10;
        boolean flag = true;//外部停止
        public void run(){
            //买票
            while(flag){
                try {
                    buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        private  void  buy() throws InterruptedException {
            //判断是否有票
            if (ticketNnums<=0){
                flag = false;
                return;
            }
            //模拟延时
            Thread.sleep(1000);
            //买票
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNnums--);
        }
    }


    这种情况会
    2.加入synchronized使方法同步,锁的是this,当前方法
    public class UnsafeBuyTicket {
        public static void main(String[] args) {
            BuyTicket station = new BuyTicket();
    
            new Thread(station,"苦逼的我").start();
            new Thread(station,"牛逼的你").start();
            new Thread(station,"可恶的黄牛党").start();
        }
    
    }
    class BuyTicket implements Runnable{
        //
        private int ticketNnums = 10;
        boolean flag = true;//外部停止
        public void run(){
            //买票
            while(flag){
                try {
                    buy();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        private synchronized void  buy() throws InterruptedException {
            //判断是否有票
            if (ticketNnums<=0){
                flag = false;
                return;
            }
            //模拟延时
            Thread.sleep(1000);
            //买票
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNnums--);
        }
    }

  • 相关阅读:
    发送trim值
    关一些时钟
    不同频率下的pwm配置
    c#鼠标在控件上面,然后显示文字
    C#通过文件路径截取对应的文件夹路径
    C#随机生成连续多少个十六进制数字
    C#检测串口被拔掉等一些触发事件合集
    c#按键Up和Down对Textbox的内容加1减1
    软件架构师工作历程
    软件架构阅读6
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12487400.html
Copyright © 2011-2022 走看看