火车售票系统以及改良版

synchronized是同步锁,当有一个线程访问上锁的代码块时,另一个线程无法访问代码块

/**
 * @author: Ren
 * @date: 2020-08-02  16:40
 * @description:
 */
public class SellTickerSys {
    private  int ticketleft = 10;
    private int ticketCount = ticketleft;
    private Object lock = new Object();

    public static void main(String[] args) {
//        创建对象实例
        SellTickerSys sellTickerSys = new SellTickerSys();
//        创建售票窗口
        Seller seller = sellTickerSys.new Seller();
        Seller seller1 = sellTickerSys.new Seller();
        Seller seller2 = sellTickerSys.new Seller();
        new Thread(seller , "售票点一").start();
        new Thread(seller1 , "售票点二").start();
        new Thread(seller2 , "售票点三").start();

    }
    class Seller implements  Runnable{
        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (ticketleft > 0) {
                        System.out.println(Thread.currentThread().getName() + "售出第" + (ticketCount + 1 - ticketleft) + "张车票");
                        ticketleft--;
                        try {
//                            模拟售票工作
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        System.out.println("车票全部售完!");
                        System.exit(0);
//                        正常离开程序
                    }
                }
            }
        }
    }
}

运行结果如下,大部分的票是售票口一售出
火车售票系统以及改良版_第1张图片
所以进行了小小的改良
/**

  • @author: Ren

  • @date: 2020-08-02 16:40

  • @description:
    */
    public class SellTickerSys {
    private int ticketleft = 10;
    private int ticketCount = ticketleft;
    private Object lock = new Object();

    public static void main(String[] args) {
    // 创建对象实例
    SellTickerSys sellTickerSys = new SellTickerSys();
    // 创建售票窗口
    Seller seller = sellTickerSys.new Seller();
    Seller seller1 = sellTickerSys.new Seller();
    Seller seller2 = sellTickerSys.new Seller();
    new Thread(seller , “售票点一”).start();
    new Thread(seller1 , “售票点二”).start();
    new Thread(seller2 , “售票点三”).start();

    }
    class Seller implements Runnable{
    @Override
    public void run() {
    while (true) {
    synchronized (lock) {
    if (ticketleft > 0) {
    System.out.println(Thread.currentThread().getName() + “售出第” + (ticketCount + 1 - ticketleft) + “张车票”);
    ticketleft–;
    }else{
    System.out.println(“车票全部售完!”);
    System.exit(0);
    // 正常离开程序
    }
    try {
    // 模拟售票工作
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
    }
    第二次·虽然解决了一直使用线程1的错误,但是也造成了逻辑上的错误,将模拟售票工作的主动睡眠挪到了外面,所以在思考后引进了线程池的技术解决这个问题,https://blog.csdn.net/weixin_44281922/article/details/107769068

你可能感兴趣的:(线程,多线程,java,并发编程,多进程)