简单安全高效的Java计数器

本文利用AtomicLong实现了一个安全高效的计数器,利用线程池技术,测试结果符合预期,避免了线程并发操作变量问题,避免使用同步锁提高了效率。

package com.springapp.mvc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by acer on 2017/5/27.
 */
public class TestAtomic {
    //AtomicLong 的api参考 http://www.tuicool.com/articles/uY3qIbB
    public static final AtomicLong atomicLong = new AtomicLong(0L);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        MyThread myThread = null;
        for(int i = 0;i<100;i++){
            myThread = new MyThread(atomicLong);
            //ExecutorService的api中文解释【启动一次顺序关闭,执行以前提交的任务,但不接受新任务】 http://tool.oschina.net/apidocs/apidoc?api=jdk-zh
            executorService.submit(myThread);
        }
        executorService.shutdown();
        System.out.println(atomicLong.get());
    }
}


class MyThread extends Thread {
    private AtomicLong atomicLong;

    public MyThread(AtomicLong atomicLong){
        this.atomicLong = atomicLong;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "正在执行。。。");
        System.out.println(atomicLong.incrementAndGet());
    }
}




你可能感兴趣的:(心情)