多线程卖票-JUC实现

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Tickets{
    private int ticket = 300;
    private Lock lock = new ReentrantLock();
     public void sale() {
         lock.lock();
         try {
             if(ticket>0) {
                System.out.println(Thread.currentThread().getName() + "\t"
                        + "卖出了" + (ticket--) +"张票,还剩下" + ticket);
             }
        } finally {
            lock.unlock();
        }
     }
}

public class SaleTickets {
    public static void main(String[] args) {
        //Lambda Express 实现
        Tickets tickets = new Tickets();
        new Thread(()->{for(int i=0; i<400; i++) tickets.sale();},"A").start();
        new Thread(()->{for(int i=0; i<400; i++) tickets.sale();},"B").start();
        new Thread(()->{for(int i=0; i<400; i++) tickets.sale();},"C").start();
    }
}


 

    原文作者:JUC
    原文地址: https://blog.csdn.net/Fighting_mjtao/article/details/83053629
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞