---
title: "java线程售票同步"
author: "825197453"
date: "2010-06-06T21:49:42Z"
tags: ["Java", "thread"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-06-06T21:49:42Z"
id: 685497
url: "https://825197453.iteye.com/blog/685497"
---

java线程的一道题

```
有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();
		} 


}
```

 

```
public class SaleTicket implements Runnable {
	private int tickets = 100;

	public void run() {
		while (true) {
			synchronized (this) {
				System.out.println(this.getClass());
				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;
				}
			}
		}
	}
}
```