日期:2014-05-17 浏览次数:20732 次
/*彩票类*/ 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); } } } }