多线程编程作业-买票

作业要求:

1、 假设现在有一个售票员进行售票,票价为5元,初始状态:票数不限,票售员手中有1张10元钱;

2、 每来一个顾客买票,相当于是创建一个线程,注意,此时顾客共享的资源是售票员及其手中的钱;

3、 当一个顾客到达后相当于创建一个线程,创建该线程时有两个参数,一是线程名,也就是顾客的名字,二是顾客带的钱(规定顾客带的钱只能为5元,10元,20元和50元)。

4、 某一个顾客买票时,如果售票员无法找零,则让该顾客等待,如果某一个顾客买票成功,则唤醒所有等待的顾客。

5、 主线程中用一个死循环来实现持续售票,可提供选择,是继续售票还是终止。

售票员售票,票价5元一张,假设只有5元,10元,20元,50元和100元五种币种,售票员手上有若干钱(自己初始化),顾客会拿这一张(5元,10元,20元,50元中的一张)钱来购票,设计一个算法,根据售票员手上的钱和顾客拿的钱判断是否可以售票?

module MaiPiao {
}
package maipiao;

public class Mythread implements Runnable{
 static int x[]=new int[5];
private int sum;
int h=0;
 Mythread (){
	for(int i=0;i<5;i++) {
		x[i]=0;
	}
	x[1]=1;
}
 public void  run() {
	 String st=Thread.currentThread().getName();
	 String str[]=st.split("-");
	 sum=Integer.valueOf(str[1]);
	 if(h==0)
	 x[1]=1;
	 synchronized(this) {
	  boolean flag=false;
	  while(flag==false) {
		  String stt=Thread.currentThread().getName();
		  String sttr[]=st.split("-");
		  sum=Integer.valueOf(sttr[1]);
		  int t=check();
	 if(t==1) {
		 h=1;
		 if(sum==5)
			 ++x[0];
		 else if(sum==10)
			 ++x[1];
		 else if(sum==20)
			 ++x[2];
		 else if(sum==50)
		     ++x[3];		 
		 else if(sum==100)
			 ++x[4];
		
		 System.out.println(Thread.currentThread().getName()+"已经买到票"); 
		 for(int j=0;j<5;j++)
		 System.out.print("x["+j+"] " +x[j]+"  ");
		 System.out.println("");
		 super.notifyAll();
		 flag=true;
	 }
	 else {
		 try {
			System.out.println(Thread.currentThread().getName()+"没买到");
			super.wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		 }
	 }
	 
	 }
	 }
 }
 public int check() {
	 int h[]=new int[5];
	 System.arraycopy(x, 0, h, 0, 5);
	 int g=0;
	 int d=sum;
	 d=d-5;
	 if(d==0)
		 return 1;
	 for(int i=4;i>=0;i--) {
		 if(h[i]>0) {
		if(i==4)
			g=100;
		else if(i==3)
			g=50;
		else if(i==2)
			g=20;
		else if(i==1)
			g=10;
		else if(i==0)
			g=5;
		while(d-g>=0) {
			d-=g;
			--h[i];
			if(h[i]<=0)
				break;
		}
		 if(d==0) {
			 System.arraycopy(h, 0, x, 0, 5);
			 return 1;
		 }
	 }
	 }
	 return 0;
 }
}


package maipiao;

import java.util.Scanner;

public class Test {

   public static void main(String[] args) {
   	Mythread d=new Mythread();
   	Scanner sc=new Scanner(System.in);
   	int flag=1;
   	String strname;
   	int money;
   	while(flag==1) {
   		System.out.println("input name");
   		strname=sc.next();
   		System.out.println("input money");
   		money=sc.nextInt();
   		Thread th=new Thread(d,strname+"-"+money);
   		th.start();
   		System.out.println("1:continue 2 :end");
   		flag=sc.nextInt();
   	}
   	
   }

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值