首页 > 编程语言 > 详细

多线程-并发卖票

时间:2019-11-10 16:22:32      阅读:87      评论:0      收藏:0      [点我收藏+]
package test;

/**
 * author:songyan
 * date: 2019/11/10
 **/
public class demo1 {
    public static void main(String[] args) {
        Tickert t = new Tickert();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        Thread t4 = new Thread(t);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class Tickert implements Runnable {
    private int number = 100;//一共一百张票
    Object obj = new Object();
    @Override
    public void run() {
        while (true) {
            synchronized (obj) {
                if (number > 0) {                   
                    System.out.println("ticket   " + number--);
                }
            }
        }
    }
}

技术分享图片技术分享图片

通过加锁防止出现错票

 

多线程-并发卖票

原文:https://www.cnblogs.com/excellencesy/p/11830323.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!