首页 > 代码库 > 关于 阿里巴巴笔试题 :投资保险的 建议

关于 阿里巴巴笔试题 :投资保险的 建议

/**
 * 
 * @author xy1131975903
 * 1)应该将保险类设计为资源共享,即设计一个同步方法用于控制用户的投资;推断是否投资成功;
 * 2)应将投资者设计为多线程类,即实现Runnable接口,能够竞争投资。
 * 3)须要在投资者中体现,竞争投资资源(保险类)的属性,即能够设计保险类为其成员变量。
 *   这样就能够体现多个用户竞争投资资源的实现。

* */ class Insurance{ private double yield=0.18; private int totalAmount=200000; private int minInvestment=1000; public int abAmount=0; private int count=0; public Insurance(){}; public synchronized boolean buySuccess(int funds,String userID){ boolean isSuccess=false; count++; System.out.println("投资: "+funds+" ; 眼下剩余: "+(totalAmount-abAmount)); if(funds%minInvestment==0 && funds<=totalAmount-abAmount){ abAmount+=funds; System.out.println("第"+count+"个用户 ("+userID+") success!"); isSuccess=true; }else{ System.out.println("第"+count+"个用户 ("+userID+") failed!"); } System.out.println(); return isSuccess; } } class User implements Runnable{ private String userID=null; private int funds=0; private Insurance mInsurance=null; public boolean isSuccess=false; public boolean isRun=false; public User(String userID,int funds,Insurance mInsurance){ this.userID=userID; this.mInsurance=mInsurance; this.funds=funds; } @Override public void run() { // TODO 自己主动生成的方法存根 isSuccess=mInsurance.buySuccess(funds,userID); isRun=true; } public String getUserId(){return userID;} public int getFunds(){return funds;} } class TestInsuracne{ public void test(){ Insurance mInsurance=new Insurance(); List<User>mList=new ArrayList<User>(); User mUser[]=new User[20]; Thread mt[]=new Thread[20]; int i=0,sleeptime=0; for(i=0;i<mUser.length;i++){ String str="userID_"+(i+1); mUser[i]=new User(str, (i+1)*1000, mInsurance); mt[i]=new Thread(mUser[i]); sleeptime=(int)Math.random()*5000; start(sleeptime, mt[i]); } //boolean exitFlag=false; while(true){ for(i=0;i<mUser.length;i++){ if(!mUser[i].isRun)break; } if(i==mUser.length)break; } System.out.println("具体数据例如以下:"); for(i=0;i<mUser.length;i++){ if(mUser[i].isSuccess){ mList.add(mUser[i]); } } User tempUser=null; for(i=0;i<mList.size();i++){ tempUser=(User)mList.get(i); System.out.println(tempUser.getUserId()+": "+tempUser.getFunds()); } } public void start(int sleepTime,Thread mt){ try { Thread.sleep(sleepTime); mt.start(); } catch (InterruptedException e) { // TODO 自己主动生成的 catch 块 e.printStackTrace(); } } }


关于 阿里巴巴笔试题 :投资保险的 建议