`
wingware
  • 浏览: 142196 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

多线性,高并发,异步非阻塞执行

阅读更多
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {  
	  
    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;  
            }  
        }  
    }  
    
}  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics