排队买票

要求:假定总票数是100张
        假设 有5个人排队卖票,同一时间只能有一个人买票
        票卖出去之后,票数要减少

代码:

/**
 * 
 */
package com.niit.homework;

/**
 * @author: Annie
 * @date:2016年6月16日
 * @description:假定总票数是100张
                                                假设 有5个人排队卖票,同一时间只能有一个人买票
                                                票卖出去之后,票数要减少
 */
public class TicketDemo implements Runnable {

    int tickt = 100;
    static    String [] name = {"张三","李四","王二","麻子","赵四"};
    @Override
    public void run() {
        while(true){
            synchronized (this) {
                if(tickt>0){
                    tickt--;
                    System.out.println(Thread.currentThread().getName()+"正在买票,其他人请耐心排队,还有"+tickt+"张票");
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {}
                }else {
                    System.out.println("票卖完了,明天再来");
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        TicketDemo ticket  = new  TicketDemo();
        Thread [] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(ticket,name[i]);
            threads[i].start();
        }

    }

}

效果图(其中一部分):

原文地址:https://www.cnblogs.com/wangmingxia/p/5591664.html