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

  • 相关阅读:
    如何用正确的方法写出高质量软件的75条体会(转)
    使用javascript动态添加onclick事件,
    签名和重载
    C#文件后缀名详解
    配置SQL Server 2005 Express的身份验证方式,以及如何启用sa登录名。
    CSS选择符及优先级计算
    关于软件版本的解释
    数据结构形象解释
    CSS属性选择符
    [转载]Repeater三层嵌套
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12487400.html
Copyright © 2011-2022 走看看