关于线程协同的火车票售卖程序

package train;

class BoundedBuffer{
	static Object lock = new Object();   //锁,保护关键区域,
	static Object emptyLock = new Object();  //用来通知是否为空的线程
	
	static int ticket=100;
	
	public Object sell() throws InterruptedException {
		synchronized (lock)//进行线程协同最好是用lock锁进行操作,不要用同步方法,也就是sychonric 加函数名这样子去同步 ,它是用自身实现wait函数的(this.wait)
                                   //,因为没有办法通知
		{
			while (ticket == 0)
			{
				synchronized (emptyLock) 
				{
					System.out.println("票已售罄,售票厅暂停服务");
					emptyLock.wait();
				}
			}
			ticket--;
			return ticket+1;
		}
	}
}

class SellThread extends Thread{
	int id;
	int sum;
	BoundedBuffer bb = null;
	SellThread(BoundedBuffer bb,int _id) {
		this.bb = bb;
		id=_id;
	}
	public void run(){
		sum=0;
		for(int i=1;i<=100;i++)
		{
			try {
			int d = (int)(1+Math.random() * 200);//必须用随机的数,因为计算机的执行是很快的,只有一个线程比另一个快一点的,那么就可以先执行完
			System.out.println();
			Thread.sleep(d);
			//Thread.sleep((int)(2000));
			int x=(int)bb.sell();
			
			sum++;
			//System.out.println("售票厅"+id+"售出第"+x+"张票");
			System.out.println(id+"________"+x);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		}
}

class test{
	public static void main(String args[])
	{
		BoundedBuffer bb = new BoundedBuffer();
		SellThread s1=new SellThread(bb,1);
		SellThread s2=new SellThread(bb,2);
		SellThread s3=new SellThread(bb,3);
		SellThread s4=new SellThread(bb,4);
		SellThread s5=new SellThread(bb,5);
		new Thread(s1).start();//队列中,随机取?五个一轮?
		new Thread(s2).start();
		new Thread(s3).start();
		new Thread(s4).start();
		new Thread(s5).start();
	}
}

题意是利用现成协同实现五个火车售票点进行同时售票,并且卖出的票号不相同

1________95

3________94

4________93

2________92

3________91

5________90

5________89
.........................

效果如上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值