关于多线程的一个问题--买票Demo

自己学习的时候仿写了一个多线程买票的问题,但是输出一直不符合预期有点疑问,求解答!~
// 一个票容器类,里面有票
public class TicketContainer {

    public volatile static Integer tickets = 50;

    public synchronized static void buy(){
        System.out.println(Thread.currentThread().getName() + "------" + tickets);
        tickets--;
    }
}

// 有很多很多的消费者买票
public class Customer implements Runnable{ @Override public void run() {
        while (TicketContainer.tickets > 0){
            TicketContainer.buy();
        }
    }
}

// 开始卖票
public class SaleTicket {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executor.submit(new Customer());
        }
    }
}

// 输出
/**
pool-1-thread-4------50
pool-1-thread-4------49
pool-1-thread-4------48
pool-1-thread-4------47
pool-1-thread-4------46
pool-1-thread-4------45
pool-1-thread-4------44
pool-1-thread-4------43
pool-1-thread-4------42
pool-1-thread-4------41
pool-1-thread-4------40
pool-1-thread-4------39
pool-1-thread-4------38
pool-1-thread-4------37
pool-1-thread-4------36
pool-1-thread-4------35
pool-1-thread-4------34
pool-1-thread-4------33
pool-1-thread-4------32
pool-1-thread-4------31
pool-1-thread-1------30
pool-1-thread-1------29
pool-1-thread-1------28
pool-1-thread-1------27
pool-1-thread-1------26
pool-1-thread-1------25
pool-1-thread-1------24
pool-1-thread-1------23
pool-1-thread-1------22
pool-1-thread-1------21
pool-1-thread-1------20
pool-1-thread-1------19
pool-1-thread-1------18
pool-1-thread-1------17
pool-1-thread-1------16
pool-1-thread-1------15
pool-1-thread-1------14
pool-1-thread-1------13
pool-1-thread-1------12
pool-1-thread-1------11
pool-1-thread-1------10
pool-1-thread-1------9
pool-1-thread-1------8
pool-1-thread-1------7
pool-1-thread-1------6
pool-1-thread-1------5
pool-1-thread-1------4
pool-1-thread-1------3
pool-1-thread-1------2
pool-1-thread-1------1
pool-1-thread-5------0     // 很奇怪
pool-1-thread-3-------1   // 为什么
pool-1-thread-2-------2   // 求解答
pool-1-thread-4-------3   // 不是同步了吗
*/
前面的购票确实是加锁同步了,疑惑的是为什么每次最后都会有几个线程输出0,1,2,3

#笔试题目#
全部评论
synchronized (SaleTicket.class) {                         while (TicketContainer.tickets > 0) {                             TicketContainer.buy();                         }                     }
点赞 回复 分享
发布于 2021-06-18 08:18
synchrinized锁整个类试试
点赞 回复 分享
发布于 2021-06-17 20:20

相关推荐

小叮当411:应该是1-3个月吧
点赞 评论 收藏
分享
点赞 评论 收藏
分享
Twilight_m...:表格简历有点难绷。说说个人看法: 1.个人基本情况里好多无意义信息,什么婚姻状况、健康状况、兴趣爱好、户口所在地、身份证号码、邮政编码,不知道的以为你填什么申请表呢。 2.校内实践个人认为对找工作几乎没帮助,建议换成和测开有关的项目,实在没得写留着也行。 3.工作经历完全看不出来是干什么的,起码看着和计算机没啥关系,建议加强描述,写点你在工作期间的实际产出、解决了什么问题。 4.个人简述大而空,看着像AI生成,感觉问题最大。“Python,C,C++成为我打造高效稳定服务的得力工具”、“我渴望凭借自身技术知识与创新能力,推动人工智能技术的应用发展,助力社会实现智能化转型”有种小学作文的美感。而且你确定你个人简述里写的你都会嘛?你AI这块写的什么“深入研究”,发几篇顶会的硕博生都不一定敢这么写。而且你AI这块的能力和软测也完全无关啊。个人简述建议写你对哪些技术栈、哪些语言、哪些生产工具的掌握,写的有条理些,而且最好是和测开强相关的。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务