public static void main(String args[]) throws Exception {
//记录开始时间 long begin = System.currentTimeMillis(); //执行范围 10000次 int count = 10000; /** 执行结果集 */ final List<String> result = new Vector<String>(); final List<String> lost_list = new Vector<String>();
List<Runnable> list = new ArrayList<Runnable>(); for(int i=0;i<count;i++){ list.add(new Runnable() { @Override public void run() { String s = Math.random()+""; try { int c = (int) (Math.random() * 1000); if(c == 5){ throw new RuntimeException("..."); } result.add(s); getSuccessAndIncrement(); } catch (Exception e) { lost_list.add(s); /** 记录错误次数 */ getAndIncrement(); } } }); } for(Runnable r : list){ new Thread(r).start(); } int success=0 ; int lost=0; while(true){ /** 获取成功数 */ success = SUCCESS_COUNT.get(); /** 获取失败数 */ lost = COUNT.get(); if(count == success+lost){ break; } } System.out.println("返回成功结果集:"+result.size()); System.out.println(">>>处理完毕,失败:"+lost); for(String s : lost_list){ System.out.println("lost:"+s); } System.out.println("运行时间:"+(System.currentTimeMillis()-begin)+"毫秒"); }
/** 记录错误的次数 */ public static final AtomicInteger COUNT = new AtomicInteger(0);
/** * 错误次数加1 * @return */ public static final void getAndIncrement() { while (true) { int current = COUNT.get(); int next = current + 1; if (COUNT.compareAndSet(current, next)) { break; } } }
/** 成功次数 */ public static final AtomicInteger SUCCESS_COUNT = new AtomicInteger(0);
/** * 成功次数加1 * @return */ public static final void getSuccessAndIncrement() { while (true) { int current = SUCCESS_COUNT.get(); int next = current + 1; if (SUCCESS_COUNT.compareAndSet(current, next)) { break; } } }