美文网首页
同步块demo-03-03

同步块demo-03-03

作者: 封_绝 | 来源:发表于2019-03-03 11:34 被阅读0次

    同步块

    package cn.ljz.cn.ljz.terminalThread;
    
    
    /**
     * Created by LIN on 2019/3/3.
     */
    public class BuyTicketTest {
        public static void main(String[] args) {
            Syn12306Web web = new Syn12306Web(10);
            new Thread(web, "lin").start();
            new Thread(web, "Mary").start();
            new Thread(web, "Sofia").start();
        }
    }
    
    class Syn12306Web implements Runnable {
        int ticketNum;
        boolean flag = true;
    
        Syn12306Web(int ticketNum) {
            this.ticketNum = ticketNum;
        }
        
        //数据安全:考虑数据完整性,不是代码完整性
        public void test() {
            //考虑没票的情况(个人认为:可能被优化到,但是也可能没有被优化到)
            if (ticketNum <= 0) {
                flag = false;
                return;
            }
            //考虑正常情况和最后一张票的情况
            synchronized (this) {
                if (ticketNum <= 0) {
                    flag = false;
                    return;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "-->" + ticketNum--);
            }
        }
    
        @Override
        public void run() {
            while (flag) {
                test();
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:同步块demo-03-03

          本文链接:https://www.haomeiwen.com/subject/vipuuqtx.html