日期:2014-05-17  浏览次数:20698 次

有两道面试题,大家帮忙做做,谢谢
1)用线程同步写一个程序来实现卖彩票,有两个类,一个是TestMain,包括100张彩票的实例;另一个是TestThread,实现了runable接口,用来卖这100张彩票。

2)有张表,结构如下:ID(key),Type(0表示全公司,1表示总部,2表示分支机构,3代表部分,4代表人员),Bid(当type=0,1,2时此字段为空,当type=3时此字段为部门ID,当Type=4是为人员Id),Bname(逻辑如上)
请写入Id=test,所属部门Id=0023,此用户属于总部的查询语句。

------解决方案--------------------
Java code

/*彩票类*/
 class Caipiao{
    private String cpName;/*彩票名称*/
    public Caipiao(String cpName){
        this.cpName=cpName;
    }
    public Caipiao SetCpName(String cp){
        this.cpName=cp;
        return this;
    }
    public String getCpName(){
        return this.cpName;
    }
}
/*包括100张彩票的实例*/
 class TestMain{
    private List<Caipiao> cplist;/*彩票集合*/
    /*生产彩票*/
    private creatCaipiao(){
       cplist=new LinkedList<Caipiao>();/*用LinkedList增删效益好*/
       for(int i=0;i<100;i++){
          Caipiao cp=new Caipiao("彩票"+i);
          cplist.add(cp);
       }
    }
    /*卖彩票的方法*/
    public synchnazied  Caipiao sellCp (){
       /*先生产彩票*/
       creatCaipiao();
       Caipiao cp=cplist.get(0);
       cplist.remove(0);
    }
}
/*用来卖这100张彩票*/
 public class TestThread implements Runnable{
    public static void main(String args0[]){
      Thread th1=new Thread(new TestThread ());  
       th1.start();  
      Thread th2=new Thread(new TestThread ());  
       th2.start();   
    }
    public void runn(){
     TestMain tm=new TestMain();
     while(true){
     try{
        Caipiao cp= tm.sellCp();
        System.out.println(cp.getCpName());
        Thread.sleep(2000); 
      }catch(Exception e){
        System.out.println(e); 
      }
     }
    }
}