java怎样制作线程安全的计数器?相信大部分人都不太了解,今天小编为了让大家更加了解java怎样制作线程安全的计数器,给大家总结了以下内容,一起往下看吧。
public class Count{
private int count = 0;
private AtomicInteger atomicI = new AtomicInteger(0);
public static void main(String[] args){
final Count cas = new Count();
List<Thread> list = new ArrayList<Thread>();
long start = System.currentTimeMillis();
for(int j=0;j<100;j++){
Thread t = new Thread(new Runnable(){
@Override
public void run(){
for(int i=0;i<1000;i++){
cas.count();
cas.safeCount();
}
}
});
list.add(t);
}
//启动线程
for(Thread t:list){
t.start();
}
//等待所有线程执行完毕
for(Thread t:list){
try{
t.join();
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println("线程不安全:"+cas.count);
System.out.println("线程安全:"+cas.atomicI.get());
System.out.println("耗时:"+(System.currentTimeMillis() - start));
}
/**线程不安全的计数器*/
public void count(){
count++;
}
/**线程安全的计数器,循环CAS*/
public void safeCount(){
for(;;){
int temp = atomicI.get();
if(atomicI.compareAndSet(temp,++temp))
break;
}
}
}执行结果:

以上就是java如何实现线程安全的计数器的内容,有需要的朋友可以参考一下,望对大家有所帮助,更多请关注天达云其它相关文章!