java 多线程 购票
来源:互联网 发布:闺蜜网络语 编辑:程序博客网 时间:2024/04/29 19:38
- package test;
- class SalesLady {
- int memontoes, five, ten;
- public synchronized String ruleForSale(int num, int money) {
- String s = null;
- if (memontoes <= 0)
- return "sorry,ticket have been sold out";
- if (money == 5) {
- if (memontoes > 0) {
- memontoes--;
- five++;
- s = "give your ticket," + "the money is just enought.";
-
- }else return "sorry,ticket have been sold out";
- } else if (money == 10) {
- while (five < 1) {
- try {
- System.out.println("No " + num + " Customer use 10 yuan to purchase ticket,please wait a moment");
- wait();
- } catch (InterruptedException e) {
- }
- }
- if (memontoes > 0) {
- memontoes--;
- five -= 1;
- ten++;
- s = "give your ticket," + "change 5 yuan.";
-
- }else return "sorry,ticket have been sold out";
- }
- notifyAll();
- return s;
- }
- SalesLady(int m, int f, int t) {
- memontoes = m;
- five = f;
- ten = t;
- }
- }
- public class SaleTick {
- static SalesLady saleslady = new SalesLady(14, 0, 0);
-
- public static void main(String[] args) {
- int moneies[] = { 5, 10, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5, 5, 10, 5};
- Thread[] aThreadArray = new Thread[20];
- System.out.println("begin to sale tickets:");
- for (int i = 0; i < moneies.length; i++) {
- aThreadArray[i] = new Thread(new CustomerClass(i + 1, moneies[i]));
- aThreadArray[i].start();
- }
- WhileLoop: while (true) {
- for (int i = 0; i < moneies.length; i++)
- if (aThreadArray[i].isAlive())
- continue WhileLoop;
- break;
- }
- System.out.println("ticket have been sold out");
- }
- }
- class CustomerClass implements Runnable {
- int num, money;
- public void run() {
- try {
- Thread.sleep(1);
- }
- catch (InterruptedException e) {
- }
- System.out.println("I'm # " + num + " Customer,use " + money + " yuan to purchase ticket,the salesman said:"
- + SaleTick.saleslady.ruleForSale(num, money));
- }
- CustomerClass(int n, int m) {
- num = n;
- money = m;
- }
- }