java火车站卖票程序(线程等待)

package com.java.thread.synch;

/**
 * 卖票演示
 * @author Administrator
 * 两个车站卖100张票
 */
public class SellTicket {
	static Object obj=new Object();
	static int Count=100;
	public static void main(String[] args){
//		StationOne one =new StationOne(obj);
//		StationTwo two =new StationTwo(obj);
//		Thread th1=new Thread(one);
//		Thread th2=new Thread(two);
//		th1.start();
//		th2.start();

		Thread th1=new Thread(new A());
		Thread th2=new Thread(new A());
		th1.setName("车站一");
		th2.setName("车站二");
		th1.start();
		th2.start();
	}
}

class A implements Runnable{
//	String obj=new String("aa");
	@SuppressWarnings("static-access")
	public void run(){
		String obj="aaa";//不能是String obj=new String("aa");aa存放在堆区
//		有两个obj,但是它们都是指向同一个aaa,aaa存放在数据区 ,数据区只有一份拷贝
		while(true){
			synchronized (obj) {
				if(SellTicket.Count>0){
					try {
						Thread.currentThread().sleep(30);
					} catch (InterruptedException e) {
//						TODO Auto-generated catch block
						e.printStackTrace();
					}
//					System.out.printf("%s卖出了第%d张票\n",Thread.currentThread().getName(),SellTicket.Count);
					System.out.println(Thread.currentThread().getName()+SellTicket.Count);
					SellTicket.Count--;
				}else{
					break;
				}
			}

		}
	}
}


/**
 * 车站一
 * @author Administrator
 *
 */
class StationOne implements Runnable{
	private Object obj;
	public StationOne(Object obj){
		this.obj=obj;
	}
	@SuppressWarnings("static-access")
	public void run() {
		synchronized(obj){
			while(SellTicket.Count>0){
				obj.notify();
				try {
					Thread.currentThread().sleep(60);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				System.out.printf("\t\t\t\t车站一卖出了第%d张票\n",SellTicket.Count);
				SellTicket.Count--;
				try {
					obj.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			obj.notify();
		}
	}
}

/**
 * 车站二
 * @author Administrator
 *
 */
class StationTwo implements Runnable{
	private Object obj;
	public StationTwo(Object obj){
		this.obj=obj;
	}
	@SuppressWarnings("static-access")
	public void run() {
		synchronized(obj){
			while(SellTicket.Count>0){
				obj.notify();
				try {
					Thread.currentThread().sleep(60);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				System.out.printf("车站二卖出了第%d张票\n",SellTicket.Count);
				SellTicket.Count--;
				try {
					obj.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			obj.notify();
		}
	}
}

posted @ 2014-12-20 10:53  生命不息大道不止  阅读(327)  评论(0)    收藏  举报