1.AtomicLong
使用AtomicLong设计一个计数器:
package com.company.atomics;
/*
* 使用原子变量类定义一个计数器
* 该计数器在整个程序中都能使用,并且在所有的地方都可以使用这个计数器,
* 这个计数器可以设计为单例
* */
import java.util.concurrent.atomic.AtomicLong;
public class Indicator {
//构造方法私有化
private Indicator(){
}
//定义一个私有的本类静态的对象
private static final Indicator INSTANCE=new Indicator();
//提供一个公共静态方法返回唯一实例
public static Indicator getInstance(){
return INSTANCE;
}
//使用原子变量类保存请求总数,成功数,失败数
private final AtomicLong requestCount=new AtomicLong(0);
private final AtomicLong successCount=new AtomicLong(0);
private final AtomicLong failureCount=new AtomicLong(0);
//有新的请求
public void requestProcessReceive(){
requestCount.incrementAndGet();
}
//处理成功
public void requestProcessSuccess(){
successCount.incrementAndGet();
}
//处理失败
public void requestProcessFailur(){
failureCount.incrementAndGet();
}
//查看总数,
public long getRequestCount(){
return requestCount.get();
}
//查看成功数
public long getSuccessCount(){
return successCount.get();
}