---
title: "售票线程"
author: "825197453"
date: "2010-06-14T18:20:06Z"
tags: ["thread"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-06-14T18:20:06Z"
id: 691992
url: "https://825197453.iteye.com/blog/691992"
---

```
/**
 * 
 * 有100张票 四个售票窗口 每个窗口代表一个线程
 *
 */
public class Test7 {
	public static void main(String[] args) {
		SaleTicket t = new SaleTicket();
		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();
		} 


}


//当前线程使用sleep()的时候那么synchronized同步就会失效,会执行其他的线程
public class SaleTicket implements Runnable {
	private int tickets = 100;

	public void run() {
		while (true) {
			synchronized (this) {
				
				if (tickets > 0) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					Thread t = Thread.currentThread();
					System.out.println(t.getName() + "卖出车票：" + tickets);
					tickets--;
				} else {
					break;
				}
			}
		}
	}
}
```