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


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;
}
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值