---
title: "java 线程 模拟卖票"
author: "bcworld"
date: "2012-05-27T13:35:43Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-05-26T22:11:24Z"
id: 1541932
url: "https://bcworld.iteye.com/blog/1541932"
---

```
package thread;
import javax.swing.JFrame;

public class Buy extends JFrame{
	static SalesLady lady=new SalesLady(19,0,0);
	
	public static void main(String []args){
	int money[]={10,10,5,10,5,10,5,5,10,5,10,5,5,10,5};
	Thread thread[]=new Thread[20];
	System.out.println("现在开始售票。。。");
	for(int i=0;i<money.length;i++){
		//创建money.length个顾客线程
		thread[i]=new Thread(new Customer(i+1,money[i]));
		//顾客开始买东西
		thread[i].start();
	}
	//检查是否所有顾客都已买完东西
	/*WhileLoop usage:*/
	 whileLoopFlag:
		while(true){
			for(int i=0;i<money.length;i++){
				if(thread[i].isAlive()){
					continue   whileLoopFlag;
				}
			}
			break;
		}
		
	System.out.println("售票结束了。");
	}
}
/**
 * 售货员
 * @author Administrator
 *
 */
class SalesLady{
	
	int items;//商品数量
	int fiveNum;//5角数量
	int tenNum;//1元数量
	private String response="";
	/**
	 * 创建售货员
	 * @param items 商品数量
	 * @param fiveNum 5角数量
	 * @param tenNum 1元数量
	 */
	public SalesLady(int items,int fiveNum,int tenNum){
		this.items=items;
		this.fiveNum=fiveNum;
		this.tenNum=tenNum;
	}
	public synchronized String ruleOfSale(int num,int money){
		//synchronized(this);
		if(items==0){
			return "已经卖完了";
		}
		if(money==5){
			fiveNum++;
			items--;
			response="给你一个纪念品，你的钱正好。";
		}
		else if(money==10){
			while(fiveNum<1){
				try {
					System.err.println(""+num+"号顾客用10元购票，发生等待！");
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			items--;
			fiveNum-=1;
			tenNum++;
			response="给你一个纪念品，你给了10元，找你5元。";
		}
		//唤起等待的现场
		this.notify();
		return response;
	}
}
/**
 * 顾客
 * @author Administrator
 *
 */
class Customer implements Runnable{
	int num;//顾客编号
	int money;//顾客使用的钱
	public Customer(int num,int money){
		this.num=num;
		this.money=money;
	}
	
	public void run() {
		try {
			Thread.sleep(300);
			System.out.println("我是"+num+"号顾客，我用"+money+"元购买纪念品，售货员说"+Buy.lady.ruleOfSale(num, money));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//System.out.println("我是"+num+"号顾客，我用"+money+"元购买纪念品，售货员说"+Buy.lady.ruleOfSale(num, money));	
	}
}
```

 

![](http://dl.iteye.com/upload/attachment/0068/7026/af8a70bd-341c-3bb3-8e6c-5d02da3c0de2.png)

 

 

![](http://dl.iteye.com/upload/attachment/0068/7032/c7d55ac0-8cda-3f57-a27d-c6085af5643c.png)