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--);
        }
    }

  • 相关阅读:
    php文件下载原理
    spring源码@configuration&@bean
    解决java在idea运行正常,但是打成jar包后中文乱码问题
    IntelliJ IDEA查看堆内存和类继承关系
    jenkins无法展示报告
    解决windows(slave)导致linux(master)输出乱码
    UIRECODER安装记录
    vue项目前后端部署
    django orm
    django笔记
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12487400.html
Copyright © 2011-2022 走看看