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

来源:互联网 发布:情景模式定时切换软件 编辑:程序博客网 时间:2024/04/27 18:59
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 blocke.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
.........................

效果如上

0 0
原创粉丝点击