ITPub博客

首页 > 应用开发 > Java > How to keep a counter atomic?

How to keep a counter atomic?

原创 Java 作者:eurt 时间:2019-05-08 20:59:42 0 删除 编辑

1 Test Case

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
// test case: who runs the most times while running simultaneously for 2 seconds
public class LongAdderDemo {
    private long count = 0;
    // synchronized
    public void testSync() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                long starttime = System.currentTimeMillis();
                while (System.currentTimeMillis() - starttime < 2000) { // 2 seconds
                    synchronized (this) {
                        ++count;
                    }
                }
                long endtime = System.currentTimeMillis();
                System.out.println("SyncThread spend:" + (endtime - starttime) + "ms" + " v" + count);
            }).start();
        }
    }
    // Atomic,based on CAS mechanism
    private AtomicLong acount = new AtomicLong(0L);
    public void testAtomic() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                long starttime = System.currentTimeMillis();
                while (System.currentTimeMillis() - starttime < 2000) { // 2 seconds
                    acount.incrementAndGet(); // acount++;
                }
                long endtime = System.currentTimeMillis();
                System.out.println("AtomicThread spend:" + (endtime - starttime) + "ms" + " v-" + acount.incrementAndGet());
            }).start();
        }
    }
    // LongAdder, more efficiently
    private LongAdder lacount = new LongAdder();
    public void testLongAdder() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                long starttime = System.currentTimeMillis();
                while (System.currentTimeMillis() - starttime < 2000) { // 2 seconds
                    lacount.increment();
                }
                long endtime = System.currentTimeMillis();
                System.out.println("LongAdderThread spend:" + (endtime - starttime) + "ms" + " v-" + lacount.sum());
            }).start();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        LongAdderDemo demo = new LongAdderDemo();
        demo.testSync();
        demo.testAtomic();
        demo.testLongAdder();
    }
}

2 Snapshot the running

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/32498/viewspace-2643747/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2012-11-02

  • 博文量
    6
  • 访问量
    3727