ITeye博客

售票线程

825197453 · 2010-06-14 18:20 · java多线程 · 编程语言 · thread · Markdown

/**
 * 
 * 有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;
				}
			}
		}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。