zoukankan      html  css  js  c++  java
  • 模拟线程安全的售票案例(java)

    package try51.thread.safe;
    
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class LockDemo {
        public static void main(String[] args) {
            // 所有票源
            ArrayList<Thread> lst = new ArrayList<>();
            lst.add(new Thread(new Tickets2("网上       售票")));
            lst.add(new Thread(new Tickets2("手机APP 售票")));
            lst.add(new Thread(new Tickets2("实地窗口售票")));
    
            // 随机产生一个客户端类型
            Random rdom = new Random();
            // 设置一个线程池
            ExecutorService es = Executors.newFixedThreadPool(100);
            // 模拟有 15个客户端 来购票
            for (int i = 0; i < 15; i++) {
                int index = rdom.nextInt(3);
                Thread thread = lst.get(index);
                // 购票线程进入线程池
                es.submit(thread);
            }
            // 关闭线程池
            es.shutdown();
        }
    }
    
    /**
     * 
     * @author lztkdr
     *
     */
    class Tickets2 implements Runnable {
    
        // 安全锁对象
        public static Lock locker = new ReentrantLock();
    
        // 静态的票总数(固定)
        public static int TicketCount = 10;
    
        public String name;
    
        /**
         * 
         * @param name
         *            客户端 票源
         */
        public Tickets2(String name) {
            this.name = name;
        }
    
        @Override
        public void run() {
            // 线程锁 队列式 售票
            locker.lock();
            try {
                // 模拟购票需要200毫秒
                Thread.sleep(200);
                if (TicketCount > 0) {
                    System.out.println(this.name + "	出售1一张,剩余	 " + (--TicketCount));
                } else {
                    System.out.println(this.name + "	沒有抢到票!!!");
                }
    
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                locker.unlock();
            }
        }
    }

  • 相关阅读:
    如何阅读修改代码
    C C++ TDD单元测试非常好的书
    应用代理 socket TCP协议 的资料
    闲聊桌面应用开发[Win16->Win32->ATL/WTL/MFC->WinForm->WPF/Silverlight/WinRT]
    MySQL sharding的几个参考地址
    ubuntu环境变量
    Angular JS | Closure | Google Web Toolkit | Dart | Polymer 概要汇集
    Linux下的应用程序性能分析 总结
    ubuntu处理中文时设置locale
    Tomcat https自制证书和浏览器配置
  • 原文地址:https://www.cnblogs.com/lztkdr/p/ThreadSafe_Ticket.html
Copyright © 2011-2022 走看看